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/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/InfoCommand.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.tools.cli.commands.bookies; import java.io.IOException; import java.math.RoundingMode; import java.text.DecimalFormat; import java.util.Map; import java.util.stream.Collectors; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookieInfoReader.BookieInfo; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.cli.helpers.CommandHelpers; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A bookie command to retrieve bookie info. */ public class InfoCommand extends BookieCommand<CliFlags> { private static final String NAME = "info"; private static final String DESC = "Retrieve bookie info such as free and total disk space."; private static final Logger LOG = LoggerFactory.getLogger(InfoCommand.class); public InfoCommand() { super(CliSpec.newBuilder() .withName(NAME) .withFlags(new CliFlags()) .withDescription(DESC) .build()); } 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 boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { ClientConfiguration clientConf = new ClientConfiguration(conf); clientConf.setDiskWeightBasedPlacementEnabled(true); try (BookKeeper bk = new BookKeeper(clientConf)) { Map<BookieId, BookieInfo> map = bk.getBookieInfo(); if (map.size() == 0) { LOG.info("Failed to retrieve bookie information from any of the bookies"); bk.close(); return true; } LOG.info("Free disk space info:"); long totalFree = 0, total = 0; for (Map.Entry<BookieId, BookieInfo> e : map.entrySet()) { BookieInfo bInfo = e.getValue(); BookieId bookieId = e.getKey(); LOG.info("{}: \tFree: {}\tTotal: {}", CommandHelpers.getBookieSocketAddrStringRepresentation(bookieId, bk.getBookieAddressResolver()), bInfo.getFreeDiskSpace() + getReadable(bInfo.getFreeDiskSpace()), bInfo.getTotalDiskSpace() + getReadable(bInfo.getTotalDiskSpace())); } // group by hostname Map<String, BookieInfo> dedupedMap = map.entrySet() .stream() .collect(Collectors.toMap( entry -> entry.getKey().toString(), entry -> entry.getValue(), (key1, key2) -> key2 )); for (BookieInfo bookieInfo : dedupedMap.values()) { totalFree += bookieInfo.getFreeDiskSpace(); total += bookieInfo.getTotalDiskSpace(); } LOG.info("Total free disk space in the cluster:\t{}", totalFree + getReadable(totalFree)); LOG.info("Total disk capacity in the cluster:\t{}", total + getReadable(total)); bk.close(); return true; } catch (IOException | InterruptedException | BKException e) { e.printStackTrace(); } return true; } }
0
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/RecoverCommand.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.tools.cli.commands.bookies; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.IOUtils; import org.apache.bookkeeper.versioning.Versioned; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to ledger data recovery for failed bookie. */ public class RecoverCommand extends BookieCommand<RecoverCommand.RecoverFlags> { private static final Logger LOG = LoggerFactory.getLogger(RecoverCommand.class); private static final String NAME = "recover"; private static final String DESC = "Recover the ledger data for failed bookie"; private static final long DEFAULT_ID = -1L; public RecoverCommand() { this(new RecoverFlags()); } private RecoverCommand(RecoverFlags flags) { super(CliSpec.<RecoverFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for recover command. */ @Accessors(fluent = true) @Setter public static class RecoverFlags extends CliFlags{ @Parameter(names = { "-l", "--ledger" }, description = "Recover a specific ledger") private long ledger = DEFAULT_ID; @Parameter(names = { "-f", "--force" }, description = "Force recovery without confirmation") private boolean force; @Parameter(names = { "-q", "--query" }, description = "Query the ledgers that contain given bookies") private boolean query; @Parameter(names = { "-dr", "--drarun" }, description = "Printing the recovery plan w/o doing actual recovery") private boolean dryRun; @Parameter(names = {"-sk", "--skipopenledgers"}, description = "Skip recovering open ledgers") private boolean skipOpenLedgers; @Parameter(names = { "-d", "--deletecookie" }, description = "Delete cookie node for the bookie") private boolean deleteCookie; @Parameter(names = { "-bs", "--bokiesrc" }, description = "Bookie address") private String bookieAddress; @Parameter(names = {"-sku", "--skipunrecoverableledgers"}, description = "Skip unrecoverable ledgers") private boolean skipUnrecoverableLedgers; @Parameter(names = { "-rate", "--replicationrate" }, description = "Replication rate in bytes") private int replicateRate; } @Override public boolean apply(ServerConfiguration conf, RecoverFlags cmdFlags) { try { return recover(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean recover(ServerConfiguration conf, RecoverFlags flags) throws IOException, BKException, InterruptedException, KeeperException { boolean query = flags.query; boolean dryrun = flags.dryRun; boolean force = flags.force; boolean skipOpenLedgers = flags.skipOpenLedgers; boolean removeCookies = !dryrun && flags.deleteCookie; boolean skipUnrecoverableLedgers = flags.skipUnrecoverableLedgers; Long ledgerId = flags.ledger; int replicateRate = flags.replicateRate; // Get bookies list final String[] bookieStrs = flags.bookieAddress.split(","); final Set<BookieId> bookieAddrs = new HashSet<>(); for (String bookieStr : bookieStrs) { try { bookieAddrs.add(BookieId.parse(bookieStr)); } catch (IllegalArgumentException err) { LOG.error("BookieSrcs has invalid bookie id format: {}", bookieStr); return false; } } if (!force) { LOG.error("Bookies : {}", bookieAddrs); if (!IOUtils.confirmPrompt("Are you sure to recover them : (Y/N)")) { LOG.error("Give up!"); return false; } } LOG.info("Constructing admin"); conf.setReplicationRateByBytes(replicateRate); ClientConfiguration adminConf = new ClientConfiguration(conf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); LOG.info("Construct admin : {}", admin); try { if (query) { return bkQuery(admin, bookieAddrs); } if (DEFAULT_ID != ledgerId) { return bkRecoveryLedger(admin, ledgerId, bookieAddrs, dryrun, skipOpenLedgers, removeCookies); } return bkRecovery(admin, bookieAddrs, dryrun, skipOpenLedgers, removeCookies, skipUnrecoverableLedgers); } finally { admin.close(); } } private boolean bkQuery(BookKeeperAdmin bkAdmin, Set<BookieId> bookieAddrs) throws InterruptedException, BKException { SortedMap<Long, LedgerMetadata> ledgersContainBookies = bkAdmin.getLedgersContainBookies(bookieAddrs); LOG.error("NOTE: Bookies in inspection list are marked with '*'."); for (Map.Entry<Long, LedgerMetadata> ledger : ledgersContainBookies.entrySet()) { LOG.info("ledger {} : {}", ledger.getKey(), ledger.getValue().getState()); Map<Long, Integer> numBookiesToReplacePerEnsemble = inspectLedger(ledger.getValue(), bookieAddrs); LOG.info("summary: ["); for (Map.Entry<Long, Integer> entry : numBookiesToReplacePerEnsemble.entrySet()) { LOG.info("{}={}, ", entry.getKey(), entry.getValue()); } LOG.info("]"); LOG.info(""); } LOG.error("Done"); return true; } private Map<Long, Integer> inspectLedger(LedgerMetadata metadata, Set<BookieId> bookiesToInspect) { Map<Long, Integer> numBookiesToReplacePerEnsemble = new TreeMap<Long, Integer>(); for (Map.Entry<Long, ? extends List<BookieId>> ensemble : metadata.getAllEnsembles().entrySet()) { List<BookieId> bookieList = ensemble.getValue(); LOG.info("{}:\t", ensemble.getKey()); int numBookiesToReplace = 0; for (BookieId bookie : bookieList) { LOG.info("{}", bookie.toString()); if (bookiesToInspect.contains(bookie)) { LOG.info("*"); ++numBookiesToReplace; } else { LOG.info(" "); } LOG.info(" "); } LOG.info(""); numBookiesToReplacePerEnsemble.put(ensemble.getKey(), numBookiesToReplace); } return numBookiesToReplacePerEnsemble; } private boolean bkRecoveryLedger(BookKeeperAdmin bkAdmin, long lid, Set<BookieId> bookieAddrs, boolean dryrun, boolean skipOpenLedgers, boolean removeCookies) throws InterruptedException, BKException { bkAdmin.recoverBookieData(lid, bookieAddrs, dryrun, skipOpenLedgers); if (removeCookies) { deleteCookies(bkAdmin.getConf(), bookieAddrs); } return true; } private void deleteCookies(ClientConfiguration conf, Set<BookieId> bookieAddrs) throws BKException { ServerConfiguration serverConf = new ServerConfiguration(conf); try { runFunctionWithRegistrationManager(serverConf, rm -> { try { for (BookieId addr : bookieAddrs) { deleteCookie(rm, addr); } } catch (Exception e) { throw new UncheckedExecutionException(e); } return null; }); } catch (Exception e) { Throwable cause = e; if (e instanceof UncheckedExecutionException) { cause = e.getCause(); } if (cause instanceof BKException) { throw (BKException) cause; } else { BKException bke = new BKException.MetaStoreException(); bke.initCause(bke); throw bke; } } } private void deleteCookie(RegistrationManager rm, BookieId bookieSrc) throws BookieException { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieSrc); cookie.getValue().deleteFromRegistrationManager(rm, bookieSrc, cookie.getVersion()); } catch (BookieException.CookieNotFoundException nne) { LOG.warn("No cookie to remove for {} : ", bookieSrc, nne); } } private boolean bkRecovery(BookKeeperAdmin bkAdmin, Set<BookieId> bookieAddrs, boolean dryrun, boolean skipOpenLedgers, boolean removeCookies, boolean skipUnrecoverableLedgers) throws InterruptedException, BKException { bkAdmin.recoverBookieData(bookieAddrs, dryrun, skipOpenLedgers, skipUnrecoverableLedgers); if (removeCookies) { deleteCookies(bkAdmin.getConf(), bookieAddrs); } return true; } }
1
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/ClusterInfoCommand.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.tools.cli.commands.bookies; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithLedgerManagerFactory; import com.google.common.annotations.VisibleForTesting; import com.google.common.util.concurrent.UncheckedExecutionException; import java.util.Iterator; import lombok.Data; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.common.util.JsonUtil; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerUnderreplicationManager; import org.apache.bookkeeper.meta.UnderreplicatedLedger; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A bookie command to retrieve bookies cluster info. */ public class ClusterInfoCommand extends BookieCommand<CliFlags> { private static final String NAME = "cluster-info"; private static final String DESC = "Exposes the current info about the cluster of bookies"; private static final Logger LOG = LoggerFactory.getLogger(ClusterInfoCommand.class); private ClusterInfo info; public ClusterInfoCommand() { super(CliSpec.newBuilder() .withName(NAME) .withFlags(new CliFlags()) .withDescription(DESC) .build()); } /** * 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 boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { ClientConfiguration clientConfiguration = new ClientConfiguration(conf); try (BookKeeperAdmin admin = new BookKeeperAdmin(clientConfiguration)) { LOG.info("Starting fill cluster info."); info = new ClusterInfo(); fillUReplicatedInfo(info, conf); fillAuditorInfo(info, admin); fillBookiesInfo(info, admin); LOG.info("--------- Cluster Info ---------"); LOG.info("{}", JsonUtil.toJson(info)); } catch (Exception e) { e.printStackTrace(); } return true; } private void fillBookiesInfo(ClusterInfo info, BookKeeperAdmin bka) throws BKException { 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, BookKeeperAdmin bka) { 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(""); } } private void fillUReplicatedInfo(ClusterInfo info, ServerConfiguration conf) throws Exception { runFunctionWithLedgerManagerFactory(conf, mFactory -> { try (LedgerUnderreplicationManager underreplicationManager = mFactory.newLedgerUnderreplicationManager()) { Iterator<UnderreplicatedLedger> iter = underreplicationManager.listLedgersToRereplicate(null); info.setClusterUnderReplicated(iter.hasNext()); info.setLedgerReplicationEnabled(underreplicationManager.isLedgerReplicationEnabled()); } catch (Exception e) { throw new UncheckedExecutionException(e); } return null; }); } @VisibleForTesting public ClusterInfo info() { return info; } }
2
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/InitCommand.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.tools.cli.commands.bookies; import com.google.common.util.concurrent.UncheckedExecutionException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; /** * Intializes new cluster by creating required znodes for the cluster. If * ledgersrootpath is already existing then it will error out. If for any * reason it errors out while creating znodes for the cluster, then before * running initnewcluster again, try nuking existing cluster by running * nukeexistingcluster. This is required because ledgersrootpath znode would * be created after verifying that it doesn't exist, hence during next retry * of initnewcluster it would complain saying that ledgersrootpath is * already existing. */ public class InitCommand extends BookieCommand<CliFlags> { private static final String NAME = "init"; private static final String DESC = "Initializes a new bookkeeper cluster. If initnewcluster fails then try nuking " + "existing cluster by running nukeexistingcluster before running initnewcluster again"; public InitCommand() { super(CliSpec.newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(new CliFlags()) .build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { try { return BookKeeperAdmin.initNewCluster(conf); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } }
3
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/DecommissionCommand.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.tools.cli.commands.bookies; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.Cookie; 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.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.Versioned; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to trigger AuditTask by resetting lostBookieRecoveryDelay and * then make sure the ledgers stored in the bookie are properly replicated * and Cookie of the decommissioned bookie should be deleted from metadata * server. */ public class DecommissionCommand extends BookieCommand<DecommissionCommand.DecommissionFlags> { static final Logger LOG = LoggerFactory.getLogger(DecommissionCommand.class); private static final String NAME = "decommission"; private static final String DESC = "Force trigger the Audittask and make sure all the ledgers stored in the decommissioning bookie" + " are replicated and cookie of the decommissioned bookie is deleted from metadata server."; public DecommissionCommand() { this(new DecommissionFlags()); } private DecommissionCommand(DecommissionFlags flags) { super(CliSpec.<DecommissionFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for decommission command. */ @Accessors(fluent = true) @Setter public static class DecommissionFlags extends CliFlags { @Parameter(names = { "-b", "--bookieid" }, description = "Decommission a remote bookie") private String remoteBookieIdToDecommission; } @Override public boolean apply(ServerConfiguration conf, DecommissionFlags cmdFlags) { try { return decommission(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean decommission(ServerConfiguration conf, DecommissionFlags flags) throws BKException, InterruptedException, IOException { ClientConfiguration adminConf = new ClientConfiguration(conf); BookKeeperAdmin admin = new BookKeeperAdmin(adminConf); try { final String remoteBookieidToDecommission = flags.remoteBookieIdToDecommission; final BookieId bookieAddressToDecommission = (StringUtils.isBlank(remoteBookieidToDecommission) ? BookieImpl.getBookieId(conf) : BookieId.parse(remoteBookieidToDecommission)); admin.decommissionBookie(bookieAddressToDecommission); LOG.info("The ledgers stored in the given decommissioning bookie: {} are properly replicated", bookieAddressToDecommission); runFunctionWithRegistrationManager(conf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieAddressToDecommission); cookie.getValue().deleteFromRegistrationManager(rm, bookieAddressToDecommission, cookie.getVersion()); } catch (BookieException.CookieNotFoundException nne) { LOG.warn("No cookie to remove for the decommissioning bookie: {}, it could be deleted already", bookieAddressToDecommission, nne); } catch (BookieException be) { throw new UncheckedExecutionException(be.getMessage(), be); } return true; }); LOG.info("Cookie of the decommissioned bookie: {} is deleted successfully", bookieAddressToDecommission); return true; } catch (Exception e) { LOG.error("Received exception in DecommissionBookieCmd ", e); return false; } finally { if (admin != null) { admin.close(); } } } }
4
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/InstanceIdCommand.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.tools.cli.commands.bookies; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.google.common.util.concurrent.UncheckedExecutionException; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to print instance id of the cluster. */ public class InstanceIdCommand extends BookieCommand<CliFlags> { static final Logger LOG = LoggerFactory.getLogger(InstanceIdCommand.class); private static final String NAME = "instanceid"; private static final String DESC = "Print the instanceid of the cluster"; public InstanceIdCommand() { super(CliSpec.newBuilder().withName(NAME).withDescription(DESC).withFlags(new CliFlags()).build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { try { runFunctionWithRegistrationManager(conf, rm -> { String readInstanceId = null; try { readInstanceId = rm.getClusterInstanceId(); } catch (BookieException e) { throw new UncheckedExecutionException(e); } LOG.info("Metadata Service Uri: {} InstanceId: {}", conf.getMetadataServiceUriUnchecked(), readInstanceId); return null; }); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } return true; } }
5
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookies/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. */ /** * Commands on operating a cluster of bookies. */ package org.apache.bookkeeper.tools.cli.commands.bookies;
6
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/CreateCookieCommand.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.tools.cli.commands.cookie; import com.beust.jcommander.Parameter; import java.io.PrintStream; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.CookieExistException; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.commands.cookie.CreateCookieCommand.Flags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.Version; import org.apache.bookkeeper.versioning.Versioned; /** * A command that create cookie. */ @Slf4j public class CreateCookieCommand extends CookieCommand<Flags> { private static final String NAME = "create"; private static final String DESC = "Create a cookie for a given bookie"; private static final String USAGE = "cookie_create Create a cookie for a given bookie\n" + " Usage: cookie_create [options]\n" + " Options:\n" + " * -cf, --cookie-file\n" + " The file to be uploaded as cookie (param format: `cookieFilePath`)"; /** * Flags to create a cookie for a given bookie. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { @Parameter( names = { "-cf", "--cookie-file" }, description = "The file to be uploaded as cookie", required = true) private String cookieFile; } public CreateCookieCommand() { this(new Flags()); } protected CreateCookieCommand(PrintStream console) { this(new Flags(), console); } public CreateCookieCommand(Flags flags) { this(flags, System.out); } private CreateCookieCommand(Flags flags, PrintStream console) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withUsage(USAGE) .withDescription(DESC) .withFlags(flags) .withConsole(console) .withArgumentsUsage("<bookie-id>") .build()); } @Override protected void apply(RegistrationManager rm, Flags cmdFlags) throws Exception { BookieId bookieId = getBookieId(cmdFlags); byte[] data = readCookieDataFromFile(cmdFlags.cookieFile); Versioned<byte[]> cookie = new Versioned<>(data, Version.NEW); try { rm.writeCookie(bookieId, cookie); } catch (CookieExistException cee) { spec.console() .println("Cookie already exist for bookie '" + bookieId + "'"); throw cee; } catch (BookieException be) { spec.console() .println("Exception on creating cookie for bookie '" + bookieId + "'"); be.printStackTrace(spec.console()); throw be; } } }
7
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/GetCookieCommand.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.tools.cli.commands.cookie; import java.io.PrintStream; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.CookieNotFoundException; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.commands.cookie.GetCookieCommand.Flags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.Versioned; /** * A command that deletes cookie. */ @Slf4j public class GetCookieCommand extends CookieCommand<Flags> { private static final String NAME = "get"; private static final String DESC = "Retrieve a cookie for a given bookie"; private static final String USAGE = "cookie_get Retrieve a cookie for a given bookie\n" + " Usage: cookie_get [options]\n" + " Options:\n" + " * <bookie-id>\n" + " The bookie-id to get (param format: `address:port`)"; /** * Flags to delete a cookie for a given bookie. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { } public GetCookieCommand() { this(new Flags()); } GetCookieCommand(PrintStream console) { this(new Flags(), console); } public GetCookieCommand(Flags flags) { this(flags, System.out); } private GetCookieCommand(Flags flags, PrintStream console) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withUsage(USAGE) .withDescription(DESC) .withFlags(flags) .withConsole(console) .withArgumentsUsage("<bookie-id>") .build()); } @Override protected void apply(RegistrationManager rm, Flags cmdFlags) throws Exception { BookieId bookieId = getBookieId(cmdFlags); try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bookieId); spec.console().println("Cookie for bookie '" + bookieId + "' is:"); spec.console().println("---"); spec.console().println( cookie.getValue() ); spec.console().println("---"); } catch (CookieNotFoundException cee) { spec.console() .println("Cookie not found for bookie '" + bookieId + "'"); throw cee; } catch (BookieException be) { spec.console() .println("Exception on getting cookie for bookie '" + bookieId + "'"); be.printStackTrace(spec.console()); throw be; } } }
8
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/DeleteCookieCommand.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.tools.cli.commands.cookie; import java.io.PrintStream; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.CookieNotFoundException; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.commands.cookie.DeleteCookieCommand.Flags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.LongVersion; /** * A command that deletes cookie. */ @Slf4j public class DeleteCookieCommand extends CookieCommand<Flags> { private static final String NAME = "delete"; private static final String DESC = "Delete a cookie for a given bookie"; private static final String USAGE = "cookie_delete Delete a cookie for a given bookie\n" + " Usage: cookie_delete [options]\n" + " Options:\n" + " * <bookie-id>\n" + " The bookie-id to be deleted (param format: `address:port`)"; /** * Flags to delete a cookie for a given bookie. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { } public DeleteCookieCommand() { this(new Flags()); } DeleteCookieCommand(PrintStream console) { this(new Flags(), console); } public DeleteCookieCommand(Flags flags) { this(flags, System.out); } private DeleteCookieCommand(Flags flags, PrintStream console) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withUsage(USAGE) .withDescription(DESC) .withFlags(flags) .withConsole(console) .withArgumentsUsage("<bookie-id>") .build()); } @Override protected void apply(RegistrationManager rm, Flags cmdFlags) throws Exception { BookieId bookieId = getBookieId(cmdFlags); try { rm.removeCookie(bookieId, new LongVersion(-1)); } catch (CookieNotFoundException cee) { spec.console() .println("Cookie not found for bookie '" + bookieId + "'"); throw cee; } catch (BookieException be) { spec.console() .println("Exception on deleting cookie for bookie '" + bookieId + "'"); be.printStackTrace(spec.console()); throw be; } } }
9
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/CookieCommand.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.tools.cli.commands.cookie; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.net.UnknownHostException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.util.concurrent.ExecutionException; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.common.net.ServiceURI; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.tools.cli.helpers.BookieShellCommand; import org.apache.bookkeeper.tools.common.BKCommand; import org.apache.bookkeeper.tools.common.BKFlags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.commons.configuration.CompositeConfiguration; /** * This is a mixin for cookie related commands to extends. */ @Slf4j abstract class CookieCommand<CookieFlagsT extends CliFlags> extends BKCommand<CookieFlagsT> { protected CookieCommand(CliSpec<CookieFlagsT> spec) { super(spec); } @Override protected boolean apply(ServiceURI serviceURI, CompositeConfiguration conf, BKFlags globalFlags, CookieFlagsT cmdFlags) { ServerConfiguration serverConf = new ServerConfiguration(); serverConf.loadConf(conf); if (null != serviceURI) { serverConf.setMetadataServiceUri(serviceURI.getUri().toString()); } try { return MetadataDrivers.runFunctionWithRegistrationManager(serverConf, registrationManager -> { try { apply(registrationManager, cmdFlags); return true; } catch (Exception e) { throw new UncheckedExecutionException(e); } }); } catch (MetadataException | ExecutionException | UncheckedExecutionException e) { Throwable cause = e; if (!(e instanceof MetadataException) && null != e.getCause()) { cause = e.getCause(); } spec.console().println("Failed to process cookie command '" + name() + "'"); cause.printStackTrace(spec.console()); return false; } } protected BookieId getBookieId(CookieFlagsT cmdFlags) throws UnknownHostException { checkArgument( cmdFlags.arguments.size() == 1, "No bookie id or more bookie ids is specified"); String bookieId = cmdFlags.arguments.get(0); try { new BookieSocketAddress(bookieId); } catch (UnknownHostException nhe) { spec.console() .println("Invalid bookie id '" + bookieId + "'is used to create cookie." + " Bookie id should be in the format of '<hostname>:<port>'"); throw nhe; } return BookieId.parse(bookieId); } protected byte[] readCookieDataFromFile(String cookieFile) throws IOException { try { return Files.readAllBytes(Paths.get(cookieFile)); } catch (NoSuchFileException nfe) { spec.console() .println("Cookie file '" + cookieFile + "' doesn't exist."); throw nfe; } } protected abstract void apply(RegistrationManager rm, CookieFlagsT cmdFlags) throws Exception; public org.apache.bookkeeper.bookie.BookieShell.Command asShellCommand(String shellCmdName, CompositeConfiguration conf) { return new BookieShellCommand<>(shellCmdName, this, conf); } }
10
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/AdminCommand.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.tools.cli.commands.cookie; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithMetadataBookieDriver; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.beust.jcommander.Parameter; import com.google.common.collect.Lists; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.bookie.LegacyCookieValidation; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.BookKeeperConstants; import org.apache.bookkeeper.util.IOUtils; import org.apache.bookkeeper.versioning.Version; import org.apache.bookkeeper.versioning.Versioned; import org.apache.commons.lang3.ArrayUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to update cookie. */ public class AdminCommand extends BookieCommand<AdminCommand.AdminFlags> { static final Logger LOG = LoggerFactory.getLogger(AdminCommand.class); private static final String NAME = "admin"; private static final String DESC = "Command to update cookie"; private File[] journalDirectories; private File[] ledgerDirectories; private File[] indexDirectories; public AdminCommand() { this(new AdminFlags()); } private AdminCommand(AdminFlags flags) { super(CliSpec.<AdminFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for admin command. */ @Accessors(fluent = true) @Setter public static class AdminFlags extends CliFlags { @Parameter(names = { "-host", "--hostname" }, description = "Expects config useHostNameAsBookieID=true as the option value") private boolean hostname; @Parameter(names = { "-p", "-ip" }, description = "Expects config useHostNameAsBookieID=false as the option value") private boolean ip; @Parameter(names = { "-e", "--expandstorage" }, description = "Add new empty ledger/index directories") private boolean expandstorage; @Parameter(names = { "-l", "--list" }, description = "List paths of all the cookies present locally and on " + "zooKeeper") private boolean list; @Parameter(names = { "-d", "--delete" }, description = "Delete cookie both locally and in zooKeeper") private boolean delete; @Parameter(names = {"-f", "--force"}, description = "Force delete cookie") private boolean force; } @Override public boolean apply(ServerConfiguration conf, AdminFlags cmdFlags) { initDirectory(conf); try { return update(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private void initDirectory(ServerConfiguration bkConf) { this.journalDirectories = BookieImpl.getCurrentDirectories(bkConf.getJournalDirs()); this.ledgerDirectories = BookieImpl.getCurrentDirectories(bkConf.getLedgerDirs()); if (null == bkConf.getIndexDirs()) { this.indexDirectories = this.ledgerDirectories; } else { this.indexDirectories = BookieImpl.getCurrentDirectories(bkConf.getIndexDirs()); } } private boolean update(ServerConfiguration conf, AdminFlags flags) throws Exception { boolean useHostName = flags.hostname; if (flags.hostname || flags.ip) { if (!conf.getUseHostNameAsBookieID() && useHostName) { LOG.error("Expects configuration useHostNameAsBookieID=true as the option value"); return false; } else if (conf.getUseHostNameAsBookieID() && !useHostName) { LOG.error("Expects configuration useHostNameAsBookieID=false as the option value"); return false; } return updateBookieIdInCookie(conf, flags.hostname); } else if (flags.expandstorage) { conf.setAllowStorageExpansion(true); return expandStorage(conf); } else if (flags.list) { return listOrDeleteCookies(conf, false, false); } else if (flags.delete) { return listOrDeleteCookies(conf, true, flags.force); } else { LOG.error("Invalid command !"); usage(); return false; } } private boolean updateBookieIdInCookie(ServerConfiguration bkConf, final boolean useHostname) throws Exception { return runFunctionWithRegistrationManager(bkConf, rm -> { try { ServerConfiguration conf = new ServerConfiguration(bkConf); String newBookieId = BookieImpl.getBookieId(conf).toString(); // read oldcookie Versioned<Cookie> oldCookie = null; try { conf.setUseHostNameAsBookieID(!useHostname); oldCookie = Cookie.readFromRegistrationManager(rm, conf); } catch (BookieException.CookieNotFoundException nne) { LOG.error("Either cookie already updated with UseHostNameAsBookieID={} or no cookie exists!", useHostname, nne); return false; } Cookie newCookie = Cookie.newBuilder(oldCookie.getValue()).setBookieId(newBookieId).build(); boolean hasCookieUpdatedInDirs = verifyCookie(newCookie, journalDirectories[0]); for (File dir : ledgerDirectories) { hasCookieUpdatedInDirs &= verifyCookie(newCookie, dir); } if (indexDirectories != ledgerDirectories) { for (File dir : indexDirectories) { hasCookieUpdatedInDirs &= verifyCookie(newCookie, dir); } } if (hasCookieUpdatedInDirs) { try { conf.setUseHostNameAsBookieID(useHostname); Cookie.readFromRegistrationManager(rm, conf); // since newcookie exists, just do cleanup of oldcookie and return conf.setUseHostNameAsBookieID(!useHostname); oldCookie.getValue().deleteFromRegistrationManager(rm, conf, oldCookie.getVersion()); return true; } catch (BookieException.CookieNotFoundException nne) { if (LOG.isDebugEnabled()) { LOG.debug("Ignoring, cookie will be written to zookeeper"); } } } else { // writes newcookie to local dirs for (File journalDirectory : journalDirectories) { newCookie.writeToDirectory(journalDirectory); LOG.info("Updated cookie file present in journalDirectory {}", journalDirectory); } for (File dir : ledgerDirectories) { newCookie.writeToDirectory(dir); } LOG.info("Updated cookie file present in ledgerDirectories {}", (Object) ledgerDirectories); if (ledgerDirectories != indexDirectories) { for (File dir : indexDirectories) { newCookie.writeToDirectory(dir); } LOG.info("Updated cookie file present in indexDirectories {}", (Object) indexDirectories); } } // writes newcookie to zookeeper conf.setUseHostNameAsBookieID(useHostname); newCookie.writeToRegistrationManager(rm, conf, Version.NEW); // delete oldcookie conf.setUseHostNameAsBookieID(!useHostname); oldCookie.getValue().deleteFromRegistrationManager(rm, conf, oldCookie.getVersion()); return true; } catch (IOException | BookieException ioe) { LOG.error("IOException during cookie updation!", ioe); return false; } }); } private boolean verifyCookie(Cookie oldCookie, File dir) throws IOException { try { Cookie cookie = Cookie.readFromDirectory(dir); cookie.verify(oldCookie); } catch (BookieException.InvalidCookieException e) { return false; } return true; } private boolean expandStorage(ServerConfiguration bkConf) throws Exception { return runFunctionWithMetadataBookieDriver(bkConf, driver -> { List<File> allLedgerDirs = Lists.newArrayList(); allLedgerDirs.addAll(Arrays.asList(ledgerDirectories)); if (indexDirectories != ledgerDirectories) { allLedgerDirs.addAll(Arrays.asList(indexDirectories)); } try (RegistrationManager registrationManager = driver.createRegistrationManager()) { LegacyCookieValidation validation = new LegacyCookieValidation(bkConf, registrationManager); List<File> dirs = Lists.newArrayList(); dirs.addAll(Arrays.asList(journalDirectories)); dirs.addAll(allLedgerDirs); validation.checkCookies(dirs); return true; } catch (BookieException e) { LOG.error("Exception while updating cookie for storage expansion", e); return false; } }); } private boolean listOrDeleteCookies(ServerConfiguration bkConf, boolean delete, boolean force) throws Exception { BookieId bookieAddress = BookieImpl.getBookieId(bkConf); File[] journalDirs = bkConf.getJournalDirs(); File[] ledgerDirs = bkConf.getLedgerDirs(); File[] indexDirs = bkConf.getIndexDirs(); File[] allDirs = ArrayUtils.addAll(journalDirs, ledgerDirs); if (indexDirs != null) { allDirs = ArrayUtils.addAll(allDirs, indexDirs); } File[] allCurDirs = BookieImpl.getCurrentDirectories(allDirs); List<File> allVersionFiles = new LinkedList<File>(); File versionFile; for (File curDir : allCurDirs) { versionFile = new File(curDir, BookKeeperConstants.VERSION_FILENAME); if (versionFile.exists()) { allVersionFiles.add(versionFile); } } if (!allVersionFiles.isEmpty()) { if (delete) { boolean confirm = force; if (!confirm) { confirm = IOUtils.confirmPrompt("Are you sure you want to delete Cookies locally?"); } if (confirm) { for (File verFile : allVersionFiles) { if (!verFile.delete()) { LOG.error("Failed to delete Local cookie file {}. So aborting deletecookie of Bookie: {}", verFile, bookieAddress); return false; } } LOG.info("Deleted Local Cookies of Bookie: {}", bookieAddress); } else { LOG.info("Skipping deleting local Cookies of Bookie: {}", bookieAddress); } } else { LOG.info("Listing local Cookie Files of Bookie: {}", bookieAddress); for (File verFile : allVersionFiles) { LOG.info(verFile.getCanonicalPath()); } } } else { LOG.info("No local cookies for Bookie: {}", bookieAddress); } return runFunctionWithRegistrationManager(bkConf, rm -> { try { Versioned<Cookie> cookie = null; try { cookie = Cookie.readFromRegistrationManager(rm, bookieAddress); } catch (BookieException.CookieNotFoundException nne) { LOG.info("No cookie for {} in metadata store", bookieAddress); return true; } if (delete) { boolean confirm = force; if (!confirm) { confirm = IOUtils.confirmPrompt("Are you sure you want to delete Cookies from metadata store?"); } if (confirm) { cookie.getValue().deleteFromRegistrationManager(rm, bkConf, cookie.getVersion()); LOG.info("Deleted Cookie from metadata store for Bookie: {}", bookieAddress); } else { LOG.info("Skipping deleting cookie from metadata store for Bookie: {}", bookieAddress); } } } catch (BookieException | IOException e) { return false; } return true; }); } }
11
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/GenerateCookieCommand.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.tools.cli.commands.cookie; import com.beust.jcommander.Parameter; import java.io.File; import java.io.PrintStream; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.bookie.Cookie.Builder; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.commands.cookie.GenerateCookieCommand.Flags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.commons.lang3.StringUtils; /** * A command that generate cookie. */ @Slf4j public class GenerateCookieCommand extends CookieCommand<Flags> { private static final String NAME = "generate"; private static final String DESC = "Generate a cookie for a given bookie"; private static final String USAGE = "cookie_generate Generate a cookie for a given bookie\n" + " Usage: cookie_generate [options]\n" + " Options:\n" + " -i, --instance-id\n" + " The instance id of the cluster that this bookie belongs to." + " If omitted, it will used the instance id of the cluster that this cli connects to. \n" + " * -j, --journal-dirs\n" + " The journal directories used by this bookie " + "(param format: `journalDir1,...,journalDirM`)\n" + " * -l, --ledger-dirs\n" + " The ledger directories used by this bookie (param format: `ledgerDir1,...,ledgerDirN`)\n" + " * -o, --output-file\n" + " The output file to save the generated cookie (param format: `cookieLocalFilePath`)\n" + " -ix, --index-dirs\n" + " The index directories used by this bookie (param format: `indexDir1,...,indexDirN`)"; /** * Flags to generate a cookie for a given bookie. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { @Parameter( names = { "-j", "--journal-dirs" }, description = "The journal directories used by this bookie", required = true) private String journalDirs; @Parameter( names = { "-l", "--ledger-dirs" }, description = "The ledger directories used by this bookie", required = true) private String ledgerDirs; @Parameter( names = { "-ix", "--index-dirs" }, description = "The index directories used by this bookie") private String indexDirs = null; @Parameter( names = { "-i", "--instance-id" }, description = "The instance id of the cluster that this bookie belongs to." + " If omitted, it will used the instance id of the cluster that this cli connects to.") private String instanceId = null; @Parameter( names = { "-o", "--output-file" }, description = "The output file to save the generated cookie.", required = true) private String outputFile; } public GenerateCookieCommand() { this(new Flags()); } GenerateCookieCommand(PrintStream console) { this(new Flags(), console); } public GenerateCookieCommand(Flags flags) { this(flags, System.out); } private GenerateCookieCommand(Flags flags, PrintStream console) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withUsage(USAGE) .withDescription(DESC) .withFlags(flags) .withConsole(console) .withArgumentsUsage("<bookie-id>") .build()); } @Override protected void apply(RegistrationManager rm, Flags cmdFlags) throws Exception { BookieId bookieId = getBookieId(cmdFlags); String instanceId; if (null == cmdFlags.instanceId) { instanceId = rm.getClusterInstanceId(); } else { instanceId = cmdFlags.instanceId; } Builder builder = Cookie.newBuilder(); builder.setBookieId(bookieId.toString()); if (StringUtils.isEmpty(instanceId)) { builder.setInstanceId(null); } else { builder.setInstanceId(instanceId); } builder.setJournalDirs(cmdFlags.journalDirs); builder.setLedgerDirs(Cookie.encodeDirPaths(cmdFlags.ledgerDirs.split(","))); if (StringUtils.isNotBlank(cmdFlags.indexDirs)) { builder.setIndexDirs(Cookie.encodeDirPaths(cmdFlags.indexDirs.split(","))); } Cookie cookie = builder.build(); cookie.writeToFile(new File(cmdFlags.outputFile)); spec.console().println("Successfully saved the generated cookie to " + cmdFlags.outputFile); } }
12
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/UpdateCookieCommand.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.tools.cli.commands.cookie; import com.beust.jcommander.Parameter; import java.io.PrintStream; import lombok.Setter; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.CookieNotFoundException; import org.apache.bookkeeper.discover.RegistrationManager; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.commands.cookie.UpdateCookieCommand.Flags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.LongVersion; import org.apache.bookkeeper.versioning.Versioned; /** * A command that updates cookie. */ @Slf4j public class UpdateCookieCommand extends CookieCommand<Flags> { private static final String NAME = "update"; private static final String DESC = "Update a cookie for a given bookie"; private static final String USAGE = "cookie_update Update a cookie for a given bookie\n" + " Usage: cookie_update [options]\n" + " Options:\n" + " * -cf, --cookie-file\n" + " The file to be uploaded as cookie (param format: `cookieFilePath`)\n" + " * <bookie-id>\n" + " Bookie ID (param format: `address:port`)"; /** * Flags to create a cookie for a given bookie. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { @Parameter( names = { "-cf", "--cookie-file" }, description = "The file to be uploaded as cookie", required = true) private String cookieFile; } public UpdateCookieCommand() { this(new Flags()); } UpdateCookieCommand(PrintStream console) { this(new Flags(), console); } public UpdateCookieCommand(Flags flags) { this(flags, System.out); } private UpdateCookieCommand(Flags flags, PrintStream console) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withUsage(USAGE) .withDescription(DESC) .withFlags(flags) .withConsole(console) .withArgumentsUsage("<bookie-id>") .build()); } @Override protected void apply(RegistrationManager rm, Flags cmdFlags) throws Exception { BookieId bookieId = getBookieId(cmdFlags); byte[] data = readCookieDataFromFile(cmdFlags.cookieFile); Versioned<byte[]> cookie = new Versioned<>(data, new LongVersion(-1L)); try { rm.writeCookie(bookieId, cookie); } catch (CookieNotFoundException cnfe) { spec.console() .println("Cookie not found for bookie '" + bookieId + "' to update"); throw cnfe; } catch (BookieException be) { spec.console() .println("Exception on updating cookie for bookie '" + bookieId + "'"); be.printStackTrace(spec.console()); throw be; } } }
13
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/cookie/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. */ /** * Cookie related cli commands. */ package org.apache.bookkeeper.tools.cli.commands.cookie;
14
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/client/DeleteLedgerCommand.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.tools.cli.commands.client; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.IOUtils; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to delete a given ledger. */ public class DeleteLedgerCommand extends BookieCommand<DeleteLedgerCommand.DeleteLedgerFlags> { private static final String NAME = "delete"; private static final String DESC = "Delete a ledger."; private static final String DEFAULT = ""; private static final Logger LOG = LoggerFactory.getLogger(DeleteLedgerCommand.class); private LedgerIdFormatter ledgerIdFormatter; public DeleteLedgerCommand() { this(new DeleteLedgerFlags()); } public DeleteLedgerCommand(LedgerIdFormatter ledgerIdFormatter) { this(new DeleteLedgerFlags()); this.ledgerIdFormatter = ledgerIdFormatter; } private DeleteLedgerCommand(DeleteLedgerFlags flags) { super(CliSpec.<DeleteLedgerCommand.DeleteLedgerFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for delete ledger command. */ @Accessors(fluent = true) @Setter public static class DeleteLedgerFlags extends CliFlags { @Parameter(names = { "-l", "--ledgerid" }, description = "Ledger ID", required = true) private long ledgerId; @Parameter(names = { "-f", "--force" }, description = "Whether to force delete the Ledger without prompt..?") private boolean force; @Parameter(names = { "-lf", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = DEFAULT; } @Override public boolean apply(ServerConfiguration conf, DeleteLedgerFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); try { return deleteLedger(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private void initLedgerIdFormatter(ServerConfiguration conf, DeleteLedgerFlags flags) { if (null == ledgerIdFormatter && !flags.ledgerIdFormatter.equals(DEFAULT)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(flags.ledgerIdFormatter, conf); } else if (null == ledgerIdFormatter && flags.ledgerIdFormatter.equals(DEFAULT)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } } private boolean deleteLedger(ServerConfiguration conf, DeleteLedgerFlags flags) throws IOException, BKException, InterruptedException { if (flags.ledgerId < 0) { LOG.error("Ledger id error."); return false; } boolean confirm = false; if (!flags.force) { confirm = IOUtils.confirmPrompt( "Are your sure to delete Ledger : " + ledgerIdFormatter.formatLedgerId(flags.ledgerId) + "?"); } BookKeeper bookKeeper = null; try { if (flags.force || confirm) { ClientConfiguration configuration = new ClientConfiguration(); configuration.addConfiguration(conf); bookKeeper = new BookKeeper(configuration); bookKeeper.deleteLedger(flags.ledgerId); } } finally { if (bookKeeper != null) { bookKeeper.close(); } } return true; } }
15
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/client/SimpleTestCommand.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.tools.cli.commands.client; import static org.apache.bookkeeper.common.concurrent.FutureUtils.result; import com.beust.jcommander.Parameter; import com.google.common.collect.ImmutableMap; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Random; import java.util.concurrent.TimeUnit; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.api.BookKeeper; import org.apache.bookkeeper.client.api.DigestType; import org.apache.bookkeeper.client.api.LedgerEntries; import org.apache.bookkeeper.client.api.LedgerEntry; import org.apache.bookkeeper.client.api.ReadHandle; import org.apache.bookkeeper.client.api.WriteHandle; import org.apache.bookkeeper.tools.cli.commands.client.SimpleTestCommand.Flags; import org.apache.bookkeeper.tools.cli.helpers.ClientCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A client command that simply tests if a cluster is healthy. */ public class SimpleTestCommand extends ClientCommand<Flags> { private static final String NAME = "simpletest"; private static final String DESC = "Simple test to create a ledger and write entries to it, then read it."; private static final Logger LOG = LoggerFactory.getLogger(SimpleTestCommand.class); /** * Flags for simple test command. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { @Parameter(names = { "-e", "--ensemble-size" }, description = "Ensemble size (default 3)") private int ensembleSize = 3; @Parameter(names = { "-w", "--write-quorum-size" }, description = "Write quorum size (default 2)") private int writeQuorumSize = 2; @Parameter(names = { "-a", "--ack-quorum-size" }, description = "Ack quorum size (default 2)") private int ackQuorumSize = 2; @Parameter(names = { "-n", "--num-entries" }, description = "Entries to write (default 100)") private int numEntries = 100; } public SimpleTestCommand() { this(new Flags()); } public SimpleTestCommand(Flags flags) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } @Override @SuppressFBWarnings({"RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", "DMI_RANDOM_USED_ONLY_ONCE"}) protected void run(BookKeeper bk, Flags flags) throws Exception { byte[] data = new byte[100]; // test data Random random = new Random(0); for (int i = 0; i < data.length; i++) { data[i] = (byte) (random.nextInt(26) + 65); } WriteHandle wh = null; try { wh = result(bk.newCreateLedgerOp() .withEnsembleSize(flags.ensembleSize) .withWriteQuorumSize(flags.writeQuorumSize) .withAckQuorumSize(flags.ackQuorumSize) .withDigestType(DigestType.CRC32C) .withCustomMetadata(ImmutableMap.of("Bookie", NAME.getBytes(StandardCharsets.UTF_8))) .withPassword(new byte[0]) .execute()); LOG.info("Ledger ID: {}", wh.getId()); long lastReport = System.nanoTime(); for (int i = 0; i < flags.numEntries; i++) { wh.append(data); if (TimeUnit.SECONDS.convert(System.nanoTime() - lastReport, TimeUnit.NANOSECONDS) > 1) { LOG.info("{} entries written", i); lastReport = System.nanoTime(); } } LOG.info("{} entries written to ledger {}", flags.numEntries, wh.getId()); try (ReadHandle rh = result(bk.newOpenLedgerOp().withLedgerId(wh.getId()).withDigestType(DigestType.CRC32C) .withPassword(new byte[0]).execute())) { LedgerEntries ledgerEntries = rh.read(0, flags.numEntries); for (LedgerEntry ledgerEntry : ledgerEntries) { if (!Arrays.equals(ledgerEntry.getEntryBytes(), data)) { LOG.error("Read test failed, the reading data is not equals writing data."); } } } } finally { if (wh != null) { wh.close(); result(bk.newDeleteLedgerOp().withLedgerId(wh.getId()).execute()); } } } }
16
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/client/LedgerMetaDataCommand.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.tools.cli.commands.client; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithLedgerManagerFactory; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.nio.file.FileSystems; import java.nio.file.Files; import java.util.Optional; import java.util.concurrent.ExecutionException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.BKException.BKLedgerExistException; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.LedgerMetadataSerDe; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.apache.bookkeeper.versioning.LongVersion; import org.apache.bookkeeper.versioning.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Print the metadata for a ledger. */ @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") public class LedgerMetaDataCommand extends BookieCommand<LedgerMetaDataCommand.LedgerMetadataFlag> { private static final String NAME = "show"; private static final String DESC = "Print the metadata for a ledger, or optionally dump to a file."; private static final String DEFAULT = ""; private static final long DEFAULT_ID = -1L; private static final Logger LOG = LoggerFactory.getLogger(LedgerMetaDataCommand.class); private LedgerMetadataSerDe serDe = new LedgerMetadataSerDe(); private LedgerIdFormatter ledgerIdFormatter; public LedgerMetaDataCommand() { this(new LedgerMetadataFlag()); } public LedgerMetaDataCommand(LedgerIdFormatter ledgerIdFormatter) { this(); this.ledgerIdFormatter = ledgerIdFormatter; } public LedgerMetaDataCommand(LedgerMetadataFlag flag) { super(CliSpec.<LedgerMetadataFlag>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flag) .build()); } /** * Flags for ledger metadata command. */ @Accessors(fluent = true) @Setter public static class LedgerMetadataFlag extends CliFlags { @Parameter(names = { "-l", "--ledgerid" }, description = "Ledger ID", required = true) private long ledgerId = DEFAULT_ID; @Parameter(names = { "-d", "--dumptofile" }, description = "Dump metadata for ledger, to a file") private String dumpToFile = DEFAULT; @Parameter(names = { "-r", "--restorefromfile" }, description = "Restore metadata for ledger, from a file") private String restoreFromFile = DEFAULT; @Parameter(names = {"-lf", "--ledgeridformatter"}, description = "Set ledger id formatter") private String ledgerIdFormatter = DEFAULT; @Parameter(names = { "-u", "--update" }, description = "Update metadata if already exist while restoring metadata") private boolean update = false; } @Override public boolean apply(ServerConfiguration conf, LedgerMetadataFlag cmdFlags) { if (!cmdFlags.ledgerIdFormatter.equals(DEFAULT) && ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else if (ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } try { return handler(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean handler(ServerConfiguration conf, LedgerMetadataFlag flag) throws MetadataException, ExecutionException { if (flag.ledgerId == DEFAULT_ID) { LOG.error("Must specific a ledger id"); return false; } runFunctionWithLedgerManagerFactory(conf, mFactory -> { try (LedgerManager m = mFactory.newLedgerManager()) { if (!flag.dumpToFile.equals(DEFAULT)) { Versioned<LedgerMetadata> md = m.readLedgerMetadata(flag.ledgerId).join(); Files.write(FileSystems.getDefault().getPath(flag.dumpToFile), serDe.serialize(md.getValue())); } else if (!flag.restoreFromFile.equals(DEFAULT)) { byte[] serialized = Files.readAllBytes( FileSystems.getDefault().getPath(flag.restoreFromFile)); LedgerMetadata md = serDe.parseConfig(serialized, flag.ledgerId, Optional.empty()); try { m.createLedgerMetadata(flag.ledgerId, md).join(); } catch (Exception be) { if (!flag.update || !(be.getCause() instanceof BKLedgerExistException)) { throw be; } m.writeLedgerMetadata(flag.ledgerId, md, new LongVersion(-1L)).join(); LOG.info("successsfully updated ledger metadata {}", flag.ledgerId); } } else { printLedgerMetadata(flag.ledgerId, m.readLedgerMetadata(flag.ledgerId).get().getValue(), true); } } catch (Exception e) { throw new UncheckedExecutionException(e); } return null; }); return true; } private void printLedgerMetadata(long ledgerId, LedgerMetadata md, boolean printMeta) { LOG.info("ledgerID: {}", ledgerIdFormatter.formatLedgerId(ledgerId)); if (printMeta) { LOG.info("{}", md.toString()); } } }
17
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/client/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. */ /** * This package contains all client related commands. */ package org.apache.bookkeeper.tools.cli.commands.client;
18
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/LedgerCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.function.Consumer; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.InterleavedLedgerStorage; import org.apache.bookkeeper.bookie.LedgerCache; import org.apache.bookkeeper.bookie.LedgerEntryPage; import org.apache.bookkeeper.bookie.SortedLedgerStorage; import org.apache.bookkeeper.bookie.storage.ldb.DbLedgerStorage; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.apache.commons.lang.mutable.MutableLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to dump ledger index entries into readable format. */ public class LedgerCommand extends BookieCommand<LedgerCommand.LedgerFlags> { static final Logger LOG = LoggerFactory.getLogger(LedgerCommand.class); private static final String NAME = "ledger"; private static final String DESC = "Dump ledger index entries into readable format"; private LedgerIdFormatter ledgerIdFormatter; private Consumer<String> print = this::printInfoLine; public void setPrint(Consumer<String> print) { this.print = print; } public LedgerCommand() { this(new LedgerFlags()); } public LedgerCommand(LedgerIdFormatter ledgerIdFormatter) { this(new LedgerFlags()); this.ledgerIdFormatter = ledgerIdFormatter; } private LedgerCommand(LedgerFlags flags) { super(CliSpec.<LedgerFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for ledger command. */ @Accessors(fluent = true) @Setter public static class LedgerFlags extends CliFlags { @Parameter(names = { "-id", "--ledgerId" }, description = "Specific ledger id", required = true) private long ledgerId; @Parameter(names = { "-m", "--meta" }, description = "Print meta information") private boolean meta; @Parameter(names = { "-l", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = ""; } @Override public boolean apply(ServerConfiguration conf, LedgerFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); long ledgerId = cmdFlags.ledgerId; if (conf.getLedgerStorageClass().equals(DbLedgerStorage.class.getName())) { // dump ledger info return dumpLedgerInfo(ledgerId, conf); } else if (conf.getLedgerStorageClass().equals(SortedLedgerStorage.class.getName()) || conf.getLedgerStorageClass().equals(InterleavedLedgerStorage.class.getName())) { ServerConfiguration tConf = new ServerConfiguration(conf); InterleavedLedgerStorage interleavedLedgerStorage = new InterleavedLedgerStorage(); try { BookieImpl.mountLedgerStorageOffline(tConf, interleavedLedgerStorage); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } if (cmdFlags.meta) { // print meta printMeta(ledgerId, interleavedLedgerStorage); } try { print.accept("===== LEDGER: " + ledgerIdFormatter.formatLedgerId(ledgerId) + " ====="); for (LedgerCache.PageEntries page : interleavedLedgerStorage.getIndexEntries(ledgerId)) { if (printPageEntries(page)) { return true; } } } catch (IOException e) { LOG.error("Failed to read index page"); return true; } } return true; } private void initLedgerIdFormatter(ServerConfiguration conf, LedgerFlags flags) { if (flags.ledgerIdFormatter.equals("")) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } else { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(flags.ledgerIdFormatter, conf); } } private boolean dumpLedgerInfo(long ledgerId, ServerConfiguration conf) { try { DbLedgerStorage.readLedgerIndexEntries(ledgerId, conf, (currentEntry, entryLodId, position) -> System.out .println("entry " + currentEntry + "\t:\t(log: " + entryLodId + ", pos: " + position + ")")); } catch (IOException e) { System.err.printf("ERROR: initializing dbLedgerStorage %s", e.getMessage()); return false; } return true; } private void printMeta(long ledgerId, InterleavedLedgerStorage interleavedLedgerStorage) { print.accept("===== LEDGER: " + ledgerIdFormatter.formatLedgerId(ledgerId) + " ====="); try { LedgerCache.LedgerIndexMetadata meta = interleavedLedgerStorage.readLedgerIndexMetadata(ledgerId); print.accept("master key : " + meta.getMasterKeyHex()); long size = meta.size; if (size % 8 == 0) { print.accept("size : " + size); } else { print.accept("size : " + size + "(not aligned with 8, may be corrupted or under flushing now)"); } print.accept("entries : " + (size / 8)); print.accept("isFenced : " + meta.fenced); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") private boolean printPageEntries(LedgerCache.PageEntries page) { final MutableLong curEntry = new MutableLong(page.getFirstEntry()); try (LedgerEntryPage lep = page.getLEP()) { lep.getEntries((entry, offset) -> { while (curEntry.longValue() < entry) { print.accept("entry " + curEntry + "\t:\tN/A"); curEntry.increment(); } long entryLogId = offset >> 32L; long pos = offset & 0xffffffffL; print.accept("entry " + curEntry + "\t:\t(log:" + entryLogId + ", pos: " + pos + ")"); curEntry.increment(); return true; }); } catch (Exception e) { print.accept( "Failed to read index page @ " + page.getFirstEntry() + ", the index file may be corrupted : " + e .getMessage()); return true; } while (curEntry.longValue() < page.getLastEntry()) { print.accept("entry " + curEntry + "\t:\tN/A"); curEntry.increment(); } return false; } private void printInfoLine(String mes) { System.out.println(mes); } }
19
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/RebuildDBLedgerLocationsIndexCommand.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.tools.cli.commands.bookie; import java.io.IOException; import org.apache.bookkeeper.bookie.storage.ldb.LocationsIndexRebuildOp; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to rebuild DBLedgerStorage locations index. */ public class RebuildDBLedgerLocationsIndexCommand extends BookieCommand<CliFlags> { static final Logger LOG = LoggerFactory.getLogger(RebuildDBLedgerLocationsIndexCommand.class); private static final String NAME = "rebuild-db-ledger-locations-index"; private static final String DESC = "Rbuild DBLedgerStorage locations index by scanning the entry logs"; public RebuildDBLedgerLocationsIndexCommand() { super(CliSpec.newBuilder().withName(NAME).withDescription(DESC).withFlags(new CliFlags()).build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { LOG.info("=== Rebuilding DBStorage locations index ==="); ServerConfiguration serverConfiguration = new ServerConfiguration(conf); try { new LocationsIndexRebuildOp(serverConfiguration).initiate(); } catch (IOException e) { e.printStackTrace(); } LOG.info("-- Done rebuilding DBStorage locations index --"); return true; } }
20
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/RebuildDBLedgersIndexCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.storage.ldb.LedgersIndexRebuildOp; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to rebuild DBLedgerStorage ledgers index. */ public class RebuildDBLedgersIndexCommand extends BookieCommand<RebuildDBLedgersIndexCommand.RebuildLedgersIndexFlags> { static final Logger LOG = LoggerFactory.getLogger(RebuildDBLedgersIndexCommand.class); private static final String NAME = "rebuild-db-ledgers-index"; private static final String DESC = "Rebuild DBLedgerStorage ledgers index by scanning the journal" + " and entry logs (sets all ledgers to fenced)"; public RebuildDBLedgersIndexCommand() { this(new RebuildLedgersIndexFlags()); } public RebuildDBLedgersIndexCommand(RebuildLedgersIndexFlags flags) { super(CliSpec.<RebuildDBLedgersIndexCommand.RebuildLedgersIndexFlags>newBuilder().withName(NAME) .withDescription(DESC).withFlags(flags).build()); } @Override public boolean apply(ServerConfiguration conf, RebuildLedgersIndexFlags cmdFlags) { LOG.info("=== Rebuilding DBStorage ledgers index ==="); ServerConfiguration serverConfiguration = new ServerConfiguration(conf); boolean success = new LedgersIndexRebuildOp(serverConfiguration, cmdFlags.verbose).initiate(); if (success) { LOG.info("-- Done rebuilding DBStorage ledgers index --"); } else { LOG.info("-- Aborted rebuilding DBStorage ledgers index --"); } return success; } /** * Flags for read log command. */ @Accessors(fluent = true) @Setter public static class RebuildLedgersIndexFlags extends CliFlags { @Parameter(names = { "-v", "--verbose" }, description = "Verbose logging. Print each ledger id found and added to the rebuilt index") private boolean verbose; } }
21
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/LastMarkCommand.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.tools.cli.commands.bookie; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.File; import java.io.IOException; import org.apache.bookkeeper.bookie.Journal; import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.bookkeeper.bookie.LogMark; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.DiskChecker; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A bookie command to print the last log marker. */ public class LastMarkCommand extends BookieCommand<CliFlags> { private static final String NAME = "lastmark"; private static final String DESC = "Print last log marker"; private static final Logger LOG = LoggerFactory.getLogger(LastMarkCommand.class); public LastMarkCommand() { super(CliSpec.newBuilder() .withName(NAME) .withFlags(new CliFlags()) .withDescription(DESC) .build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags flags) { try { LedgerDirsManager dirsManager = new LedgerDirsManager( conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); File[] journalDirs = conf.getJournalDirs(); for (int idx = 0; idx < journalDirs.length; idx++) { Journal journal = new Journal(idx, journalDirs[idx], conf, dirsManager); LogMark lastLogMark = journal.getLastLogMark().getCurMark(); LOG.info("LastLogMark : Journal Id - {}({}.txn), Pos - {}", lastLogMark.getLogFileId(), Long.toHexString(lastLogMark.getLogFileId()), lastLogMark.getLogFileOffset()); } return true; } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } }
22
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ListFilesOnDiscCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.File; import java.io.IOException; import java.util.List; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieShell; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to list the files in JournalDirectory/LedgerDirectories/IndexDirectories. */ public class ListFilesOnDiscCommand extends BookieCommand<ListFilesOnDiscCommand.LFODFlags > { private static final String NAME = "listfilesondisc"; private static final String DESC = "List the files in JournalDirectory/LedgerDirectories/IndexDirectories."; private static final Logger LOG = LoggerFactory.getLogger(ListFilesOnDiscCommand.class); public ListFilesOnDiscCommand() { this(new LFODFlags()); } public ListFilesOnDiscCommand(LFODFlags flags) { super(CliSpec.<LFODFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for list files on disc command. */ @Accessors(fluent = true) @Setter public static class LFODFlags extends CliFlags { @Parameter(names = {"-txn", "--journal"}, description = "Print list of Journal Files") private boolean journal; @Parameter(names = {"-log", "--entrylog"}, description = "Print list of EntryLog Files") private boolean entrylog; @Parameter(names = {"-idx", "--index"}, description = "Print list of Index Files") private boolean index; } @Override public boolean apply(ServerConfiguration conf, LFODFlags cmdFlags) { try { return handler(conf, cmdFlags); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean handler(ServerConfiguration conf, LFODFlags cmd) throws IOException { if (cmd.journal) { File[] journalDirs = conf.getJournalDirs(); List<File> journalFiles = BookieShell.listFilesAndSort(journalDirs, "txn"); LOG.info("--------- Printing the list of Journal Files ---------"); for (File journalFile : journalFiles) { LOG.info("{}", journalFile.getCanonicalPath()); } LOG.info(""); } if (cmd.entrylog) { File[] ledgerDirs = conf.getLedgerDirs(); List<File> ledgerFiles = BookieShell.listFilesAndSort(ledgerDirs, "log"); LOG.info("--------- Printing the list of EntryLog/Ledger Files ---------"); for (File ledgerFile : ledgerFiles) { LOG.info("{}", ledgerFile.getCanonicalPath()); } LOG.info(""); } if (cmd.index) { File[] indexDirs = (conf.getIndexDirs() == null) ? conf.getLedgerDirs() : conf.getIndexDirs(); List<File> indexFiles = BookieShell.listFilesAndSort(indexDirs, "idx"); LOG.info("--------- Printing the list of Index Files ---------"); for (File indexFile : indexFiles) { LOG.info("{}", indexFile.getCanonicalPath()); } } return true; } }
23
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/RegenerateInterleavedStorageIndexFileCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.beust.jcommander.converters.CommaParameterSplitter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.InterleavedStorageRegenerateIndexOp; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to regenerate an index file for interleaved storage. */ public class RegenerateInterleavedStorageIndexFileCommand extends BookieCommand<RegenerateInterleavedStorageIndexFileCommand.RISIFFlags> { static final Logger LOG = LoggerFactory.getLogger(RegenerateInterleavedStorageIndexFileCommand.class); private static final String NAME = "regenerate-interleaved-storage-index-file"; private static final String DESC = "Regenerate an interleaved storage index file, from available entrylogger " + "files."; private static final String DEFAULT = ""; public RegenerateInterleavedStorageIndexFileCommand() { this(new RISIFFlags()); } private RegenerateInterleavedStorageIndexFileCommand(RISIFFlags flags) { super(CliSpec.<RISIFFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for regenerate interleaved storage index file command. */ @Accessors(fluent = true) @Setter public static class RISIFFlags extends CliFlags { @Parameter(names = { "-p", "--password" }, description = "The bookie stores the password in the index file, so we need it to regenerate." + "This must match the value in the ledger metadata.") private String password = DEFAULT; @Parameter(names = { "-b", "--b64password" }, description = "The password in base64 encoding, for cases where the password is not UTF-8.") private String b64Password = DEFAULT; @Parameter(names = { "-d", "--dryrun" }, description = "Process the entryLogger, but don't write anthing.") private boolean dryRun; @Parameter(names = { "-l", "--ledgerids" }, description = "Ledger(s) whose index needs to be regenerated. Multiple can be specified, comma separated.", splitter = CommaParameterSplitter.class) private List<Long> ledgerIds; } @Override public boolean apply(ServerConfiguration conf, RISIFFlags cmdFlags) { try { return generate(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean generate(ServerConfiguration conf, RISIFFlags flags) throws NoSuchAlgorithmException, IOException { validateFlags(flags); byte[] password; if (!flags.password.equals(DEFAULT)) { password = flags.password.getBytes(StandardCharsets.UTF_8); } else if (!flags.b64Password.equals(DEFAULT)) { password = Base64.getDecoder().decode(flags.b64Password); } else { LOG.error("The password must be specified to regenerate the index file"); return false; } Set<Long> ledgerIds = flags.ledgerIds.stream().collect(Collectors.toSet()); LOG.info("=== Rebuilding index file for {} ===", ledgerIds); ServerConfiguration serverConfiguration = new ServerConfiguration(conf); InterleavedStorageRegenerateIndexOp i = new InterleavedStorageRegenerateIndexOp(serverConfiguration, ledgerIds, password); i.initiate(flags.dryRun); LOG.info("-- Done rebuilding index file for {} --", ledgerIds); return true; } private void validateFlags(RISIFFlags flags) { if (flags.password == null) { flags.password = DEFAULT; } if (flags.b64Password == null) { flags.b64Password = DEFAULT; } } }
24
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ConvertToDBStorageCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.InterleavedLedgerStorage; import org.apache.bookkeeper.bookie.LedgerCache; import org.apache.bookkeeper.bookie.storage.ldb.DbLedgerStorage; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A command to convert bookie indexes from InterleavedStorage to DbLedgerStorage format. */ public class ConvertToDBStorageCommand extends BookieCommand<ConvertToDBStorageCommand.CTDBFlags> { private static final Logger LOG = LoggerFactory.getLogger(ConvertToDBStorageCommand.class); private static final String NAME = "converttodbstorage"; private static final String DESC = "Convert bookie indexes from InterleavedStorage to DbLedgerStorage format"; private static final String NOT_INIT = "default formatter"; @Setter private LedgerIdFormatter ledgerIdFormatter; public ConvertToDBStorageCommand() { this(new CTDBFlags()); } public ConvertToDBStorageCommand(CTDBFlags flags) { super(CliSpec.<CTDBFlags>newBuilder().withFlags(flags).withName(NAME).withDescription(DESC).build()); } /** * Flags for this command. */ @Accessors(fluent = true) @Setter public static class CTDBFlags extends CliFlags { @Parameter(names = { "-l", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = NOT_INIT; } @Override public boolean apply(ServerConfiguration conf, CTDBFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); try { return handle(conf); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean handle(ServerConfiguration conf) throws Exception { LOG.info("=== Converting to DbLedgerStorage ==="); ServerConfiguration bkConf = new ServerConfiguration(conf); InterleavedLedgerStorage interleavedStorage = new InterleavedLedgerStorage(); BookieImpl.mountLedgerStorageOffline(bkConf, interleavedStorage); DbLedgerStorage dbStorage = new DbLedgerStorage(); BookieImpl.mountLedgerStorageOffline(bkConf, dbStorage); int convertedLedgers = 0; for (long ledgerId : interleavedStorage.getActiveLedgersInRange(0, Long.MAX_VALUE)) { if (LOG.isDebugEnabled()) { LOG.debug("Converting ledger {}", ledgerIdFormatter.formatLedgerId(ledgerId)); } LedgerCache.LedgerIndexMetadata fi = interleavedStorage.readLedgerIndexMetadata(ledgerId); LedgerCache.PageEntriesIterable pages = interleavedStorage.getIndexEntries(ledgerId); long numberOfEntries = dbStorage.addLedgerToIndex(ledgerId, fi.fenced, fi.masterKey, pages); if (LOG.isDebugEnabled()) { LOG.debug(" -- done. fenced={} entries={}", fi.fenced, numberOfEntries); } // Remove index from old storage interleavedStorage.deleteLedger(ledgerId); if (++convertedLedgers % 1000 == 0) { LOG.info("Converted {} ledgers", convertedLedgers); } } dbStorage.shutdown(); interleavedStorage.shutdown(); LOG.info("---- Done Converting ----"); return true; } private void initLedgerIdFormatter(ServerConfiguration conf, CTDBFlags flags) { if (this.ledgerIdFormatter != null) { return; } if (flags.ledgerIdFormatter.equals(NOT_INIT)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } else { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(flags.ledgerIdFormatter, conf); } } }
25
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/CheckDBLedgersIndexCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import java.io.IOException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.storage.ldb.LedgersIndexCheckOp; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to check the DBLedgerStorage ledgers index integrity. */ public class CheckDBLedgersIndexCommand extends BookieCommand<CheckDBLedgersIndexCommand.CheckLedgersIndexFlags> { static final Logger LOG = LoggerFactory.getLogger(CheckDBLedgersIndexCommand.class); private static final String NAME = "check-db-ledgers-index"; private static final String DESC = "Check the DBLedgerStorage ledgers index integrity by performing a read scan"; public CheckDBLedgersIndexCommand() { this(new CheckLedgersIndexFlags()); } public CheckDBLedgersIndexCommand(CheckLedgersIndexFlags flags) { super(CliSpec.<CheckLedgersIndexFlags>newBuilder().withName(NAME) .withDescription(DESC).withFlags(flags).build()); } @Override public boolean apply(ServerConfiguration conf, CheckLedgersIndexFlags cmdFlags) { LOG.info("=== Checking DBStorage ledgers index by running a read scan ==="); ServerConfiguration serverConfiguration = new ServerConfiguration(conf); try { boolean success = new LedgersIndexCheckOp(serverConfiguration, cmdFlags.verbose).initiate(); if (success) { LOG.info("-- Done checking DBStorage ledgers index --"); } else { LOG.info("-- Aborted checking DBStorage ledgers index --"); } return success; } catch (IOException e) { e.printStackTrace(); return false; } } /** * Flags for read log command. */ @Accessors(fluent = true) @Setter public static class CheckLedgersIndexFlags extends CliFlags { @Parameter(names = { "-v", "--verbose" }, description = "Verbose logging. Print each ledger.") private boolean verbose; } }
26
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ReadJournalCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.collect.Lists; import com.google.common.util.concurrent.UncheckedExecutionException; import io.netty.buffer.Unpooled; import java.io.File; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.Journal; import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.BookKeeperConstants; import org.apache.bookkeeper.util.DiskChecker; import org.apache.bookkeeper.util.EntryFormatter; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to scan a journal file and format the entries into readable format. */ public class ReadJournalCommand extends BookieCommand<ReadJournalCommand.ReadJournalFlags> { private static final String NAME = "readjournal"; private static final String DESC = "Scan a journal file and format the entries into readable format."; private static final long DEFAULT_JOURNALID = -1L; private static final String DEFAULT = ""; private LedgerIdFormatter ledgerIdFormatter; private EntryFormatter entryFormatter; private static final Logger LOG = LoggerFactory.getLogger(ReadJournalCommand.class); List<Journal> journals = null; public ReadJournalCommand() { this(new ReadJournalFlags()); } public ReadJournalCommand(LedgerIdFormatter idFormatter, EntryFormatter entryFormatter) { this(new ReadJournalFlags()); this.ledgerIdFormatter = idFormatter; this.entryFormatter = entryFormatter; } ReadJournalCommand(ReadJournalFlags flags) { super(CliSpec.<ReadJournalFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flag for read journal command. */ @Accessors(fluent = true) @Setter public static class ReadJournalFlags extends CliFlags { @Parameter(names = {"-m", "--msg"}, description = "Print message body") private boolean msg; @Parameter(names = { "-d", "--dir" }, description = "Journal directory (needed if more than one journal " + "configured)") private String dir = DEFAULT; @Parameter(names = {"-id", "--journalid"}, description = "Journal Id") private long journalId = DEFAULT_JOURNALID; @Parameter(names = {"-f", "--filename"}, description = "Journal file name") private String fileName = DEFAULT; @Parameter(names = {"-l", "--ledgerIdFormatter"}, description = "Set ledger id formatter") private String ledgerIdFormatter = DEFAULT; @Parameter(names = {"-e", "--entryformatter"}, description = "set entry formatter") private String entryFormatter = DEFAULT; } @Override public boolean apply(ServerConfiguration conf, ReadJournalFlags cmdFlags) { initTools(conf, cmdFlags); if (!checkArgs(cmdFlags)) { return false; } try { return handler(conf, cmdFlags); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private void initTools(ServerConfiguration conf, ReadJournalFlags flags) { if (!flags.ledgerIdFormatter.equals(DEFAULT)) { ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(flags.ledgerIdFormatter, conf); } else { ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } if (!flags.entryFormatter.equals(DEFAULT)) { entryFormatter = EntryFormatter.newEntryFormatter(flags.entryFormatter, conf); } else { entryFormatter = EntryFormatter.newEntryFormatter(conf); } } private boolean handler(ServerConfiguration conf, ReadJournalFlags cmd) throws IOException { Journal journal = null; if (getJournals(conf).size() > 1) { if (cmd.dir.equals(DEFAULT)) { LOG.error("ERROR: invalid or missing journal directory"); usage(); return false; } File journalDirectory = new File(cmd.dir); for (Journal j : getJournals(conf)) { if (j.getJournalDirectory().equals(journalDirectory)) { journal = j; break; } } if (journal == null) { LOG.error("ERROR: journal directory not found"); usage(); return false; } } else { journal = getJournals(conf).get(0); } long journalId = cmd.journalId; if (cmd.journalId == DEFAULT_JOURNALID && !cmd.fileName.equals(DEFAULT)) { File f = new File(cmd.fileName); String name = f.getName(); if (!name.endsWith(".txn")) { LOG.error("ERROR: invalid journal file name {}", cmd.fileName); usage(); return false; } String idString = name.split("\\.")[0]; journalId = Long.parseLong(idString, 16); } scanJournal(journal, journalId, cmd.msg); return true; } private boolean checkArgs(ReadJournalFlags flags) { if ((flags.fileName.equals(DEFAULT) && flags.journalId == DEFAULT_JOURNALID)) { LOG.info("ERROR: You should figure jounalId or journal filename"); return false; } return true; } private synchronized List<Journal> getJournals(ServerConfiguration conf) throws IOException { if (null == journals) { journals = Lists.newArrayListWithCapacity(conf.getJournalDirs().length); int idx = 0; for (File journalDir : conf.getJournalDirs()) { journals.add(new Journal(idx++, new File(journalDir, BookKeeperConstants.CURRENT_DIR), conf, new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())))); } } return journals; } /** * Scan a journal file. * * @param journalId Journal File Id * @param printMsg Whether printing the entry data. */ private void scanJournal(Journal journal, long journalId, final boolean printMsg) throws IOException { LOG.info("Scan journal {} ({}.txn)", journalId, Long.toHexString(journalId)); scanJournal(journal, journalId, new Journal.JournalScanner() { boolean printJournalVersion = false; @Override public void process(int journalVersion, long offset, ByteBuffer entry) throws IOException { if (!printJournalVersion) { LOG.info("Journal Version : {}", journalVersion); printJournalVersion = true; } FormatUtil .formatEntry(offset, Unpooled.wrappedBuffer(entry), printMsg, ledgerIdFormatter, entryFormatter); } }); } private void scanJournal(Journal journal, long journalId, Journal.JournalScanner scanner) throws IOException { journal.scanJournal(journalId, 0L, scanner, false); } }
27
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ListLedgersCommand.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.tools.cli.commands.bookie; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithLedgerManagerFactory; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.net.UnknownHostException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.api.LedgerMetadata; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks; import org.apache.bookkeeper.tools.cli.commands.bookie.ListLedgersCommand.ListLedgersFlags; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command for list all ledgers on the cluster. */ @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") public class ListLedgersCommand extends BookieCommand<ListLedgersFlags> { private static final Logger LOG = LoggerFactory.getLogger(ListLedgersCommand.class); private static final String NAME = "listledgers"; private static final String DESC = "List all ledgers on the cluster (this may take a long time)."; private static final String DEFAULT = ""; private LedgerIdFormatter ledgerIdFormatter; public ListLedgersCommand() { this(new ListLedgersFlags()); } public ListLedgersCommand(LedgerIdFormatter ledgerIdFormatter) { this(new ListLedgersFlags()); this.ledgerIdFormatter = ledgerIdFormatter; } public ListLedgersCommand(ListLedgersFlags flags) { super(CliSpec.<ListLedgersFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for ListLedgers command. */ @Accessors(fluent = true) @Setter public static class ListLedgersFlags extends CliFlags{ @Parameter(names = {"-m", "--meta"}, description = "Print metadata") private boolean meta; @Parameter(names = { "-id", "--bookieid" }, description = "List ledgers residing in this bookie") private String bookieId; @Parameter(names = { "-l", "--ledgerIdFormatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = DEFAULT; } @Override public boolean apply(ServerConfiguration conf, ListLedgersFlags cmdFlags) { initLedgerFrommat(conf, cmdFlags); try { handler(conf, cmdFlags); } catch (UnknownHostException e) { LOG.error("Bookie id error"); return false; } catch (MetadataException | ExecutionException e) { throw new UncheckedExecutionException(e.getMessage(), e); } return true; } private void initLedgerFrommat(ServerConfiguration conf, ListLedgersFlags cmdFlags) { if (ledgerIdFormatter != null) { return; } if (!cmdFlags.ledgerIdFormatter.equals(DEFAULT)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } } public boolean handler(ServerConfiguration conf, ListLedgersFlags flags) throws UnknownHostException, MetadataException, ExecutionException { final BookieId bookieAddress = StringUtils.isBlank(flags.bookieId) ? null : BookieId.parse(flags.bookieId); runFunctionWithLedgerManagerFactory(conf, mFactory -> { try (LedgerManager ledgerManager = mFactory.newLedgerManager()) { final AtomicInteger returnCode = new AtomicInteger(BKException.Code.OK); final CountDownLatch processDone = new CountDownLatch(1); BookkeeperInternalCallbacks.Processor<Long> ledgerProcessor = (ledgerId, cb) -> { if (!flags.meta && (bookieAddress == null)) { printLedgerMetadata(ledgerId, null, false); cb.processResult(BKException.Code.OK, null, null); } else { ledgerManager.readLedgerMetadata(ledgerId).whenComplete((metadata, exception) -> { if (exception == null) { if ((bookieAddress == null) || BookKeeperAdmin.areEntriesOfLedgerStoredInTheBookie (ledgerId, bookieAddress, metadata.getValue())) { /* * the print method has to be in * synchronized scope, otherwise * output of printLedgerMetadata * could interleave since this * callback for different * ledgers can happen in * different threads. */ synchronized (ListLedgersCommand.this) { printLedgerMetadata(ledgerId, metadata.getValue(), flags.meta); } } cb.processResult(BKException.Code.OK, null, null); } else if (BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsException || BKException.getExceptionCode(exception) == BKException.Code.NoSuchLedgerExistsOnMetadataServerException) { cb.processResult(BKException.Code.OK, null, null); } else { LOG.error("Unable to read the ledger: {} information", ledgerId); cb.processResult(BKException.getExceptionCode(exception), null, null); } }); } }; ledgerManager.asyncProcessLedgers(ledgerProcessor, (rc, s, obj) -> { returnCode.set(rc); processDone.countDown(); }, null, BKException.Code.OK, BKException.Code.ReadException); processDone.await(); if (returnCode.get() != BKException.Code.OK) { LOG.error("Received error return value while processing ledgers: {}", returnCode.get()); throw BKException.create(returnCode.get()); } } catch (Exception ioe) { LOG.error("Received Exception while processing ledgers", ioe); throw new UncheckedExecutionException(ioe); } return null; }); return true; } private void printLedgerMetadata(long ledgerId, LedgerMetadata md, boolean printMeta) { LOG.info("ledgerID: {}", ledgerIdFormatter.formatLedgerId(ledgerId)); if (printMeta) { LOG.info("{}", md.toString()); } } }
28
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/LocalConsistencyCheckCommand.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.tools.cli.commands.bookie; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.util.List; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.LedgerStorage; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to check local storage for inconsistencies. */ public class LocalConsistencyCheckCommand extends BookieCommand<CliFlags> { static final Logger LOG = LoggerFactory.getLogger(LocalConsistencyCheckCommand.class); private static final String NAME = "localconsistencycheck"; private static final String DESC = "Validate Ledger Storage internal metadata"; public LocalConsistencyCheckCommand() { super(CliSpec.newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(new CliFlags()) .build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { try { return check(conf); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean check(ServerConfiguration conf) throws IOException { LOG.info("=== Performing local consistency check ==="); ServerConfiguration serverConfiguration = new ServerConfiguration(conf); LedgerStorage ledgerStorage = BookieImpl.mountLedgerStorageOffline(serverConfiguration, null); List<LedgerStorage.DetectedInconsistency> errors = ledgerStorage.localConsistencyCheck( java.util.Optional.empty()); if (errors.size() > 0) { LOG.info("=== Check returned errors: ==="); for (LedgerStorage.DetectedInconsistency error : errors) { LOG.error("Ledger {}, entry {}: ", error.getLedgerId(), error.getEntryId(), error.getException()); } return false; } else { LOG.info("=== Check passed ==="); return true; } } }
29
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ReadLogMetadataCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.IOException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.EntryLogMetadata; import org.apache.bookkeeper.bookie.ReadOnlyDefaultEntryLogger; import org.apache.bookkeeper.bookie.storage.EntryLogger; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.commands.bookie.ReadLogMetadataCommand.ReadLogMetadataFlags; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to print metadata of entry log. */ public class ReadLogMetadataCommand extends BookieCommand<ReadLogMetadataFlags> { static final Logger LOG = LoggerFactory.getLogger(ReadLogMetadataCommand.class); private static final String NAME = "readlogmetadata"; private static final String DESC = "Prints entrylog's metadata"; private static final long DEFAULT_LOGID = -1L; private static final String DEFAULT_FILENAME = ""; private static final String DEFAULT = ""; private LedgerIdFormatter ledgerIdFormatter; EntryLogger entryLogger = null; public ReadLogMetadataCommand() { this(new ReadLogMetadataFlags()); } public ReadLogMetadataCommand(LedgerIdFormatter ledgerIdFormatter) { this(new ReadLogMetadataFlags()); this.ledgerIdFormatter = ledgerIdFormatter; } private ReadLogMetadataCommand(ReadLogMetadataFlags flags) { super(CliSpec.<ReadLogMetadataFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for read log metadata command. */ @Accessors(fluent = true) @Setter public static class ReadLogMetadataFlags extends CliFlags { @Parameter(names = { "-l", "--logid" }, description = "Entry log id") private long logId; @Parameter(names = { "-f", "--filename" }, description = "Entry log filename") private String logFilename; @Parameter(names = { "-lf", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = DEFAULT; } @Override public boolean apply(ServerConfiguration conf, ReadLogMetadataFlags cmdFlags) { if (!cmdFlags.ledgerIdFormatter.equals(DEFAULT) && ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else if (ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } if (cmdFlags.logId == DEFAULT_LOGID && cmdFlags.logFilename.equals(DEFAULT_FILENAME)) { LOG.error("Missing entry log id or entry log file name"); return false; } try { return readLogMetadata(conf, cmdFlags); } catch (IOException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } public boolean readLogMetadata(ServerConfiguration conf, ReadLogMetadataFlags flags) throws IOException { long logid = DEFAULT_LOGID; if (flags.logId != DEFAULT_LOGID) { logid = flags.logId; } else if (!flags.logFilename.equals(DEFAULT_FILENAME)) { File f = new File(flags.logFilename); String name = f.getName(); if (!name.endsWith(".log")) { LOG.error("ERROR: invalid entry log file name " + flags.logFilename); return false; } String idString = name.split("\\.")[0]; logid = Long.parseLong(idString, 16); } printEntryLogMetadata(conf, logid); return true; } private void printEntryLogMetadata(ServerConfiguration conf, long logId) throws IOException { LOG.info("Print entryLogMetadata of entrylog {} ({}.log)", logId, Long.toHexString(logId)); initEntryLogger(conf); EntryLogMetadata entryLogMetadata = entryLogger.getEntryLogMetadata(logId); LOG.info("entryLogId: {}, remaining size: {}, total size: {}, usage: {}", entryLogMetadata.getEntryLogId(), entryLogMetadata.getRemainingSize(), entryLogMetadata.getTotalSize(), entryLogMetadata.getUsage()); entryLogMetadata.getLedgersMap().forEach((ledgerId, size) -> { LOG.info("--------- Lid={}, TotalSizeOfEntriesOfLedger={} ---------", ledgerIdFormatter.formatLedgerId(ledgerId), size); }); } @SuppressFBWarnings("IS2_INCONSISTENT_SYNC") private synchronized void initEntryLogger(ServerConfiguration conf) throws IOException { // provide read only entry logger if (null == entryLogger) { entryLogger = new ReadOnlyDefaultEntryLogger(conf); } } }
30
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/InitCommand.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.tools.cli.commands.bookie; import com.google.common.util.concurrent.UncheckedExecutionException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; /** * A command to initialize new bookie. */ public class InitCommand extends BookieCommand<CliFlags> { private static final String NAME = "init"; private static final String DESC = "Initialize new bookie."; public InitCommand() { super(CliSpec.newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(new CliFlags()) .build()); } @Override public boolean apply(ServerConfiguration conf, CliFlags cmdFlags) { boolean result = false; try { result = BookKeeperAdmin.initBookie(conf); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } return result; } }
31
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/SanityTestCommand.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.tools.cli.commands.bookie; import static java.nio.charset.StandardCharsets.UTF_8; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.LocalBookieEnsemblePlacementPolicy; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.commands.bookie.SanityTestCommand.SanityFlags; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A bookie command to sanity test for local bookie. */ public class SanityTestCommand extends BookieCommand<SanityFlags> { private static final Logger LOG = LoggerFactory.getLogger(SanityTestCommand.class); private static final String NAME = "sanitytest"; private static final String DESC = "Sanity test for local bookie. " + "Create ledger and write/reads entries on local bookie."; public SanityTestCommand() { this(new SanityFlags()); } public SanityTestCommand(SanityFlags flags) { super(CliSpec.<SanityFlags>newBuilder().withFlags(flags).withName(NAME).withDescription(DESC).build()); } /** * Flags for sanity command. */ @Accessors(fluent = true) @Setter public static class SanityFlags extends CliFlags{ @Parameter(names = {"-e", "--entries"}, description = "Total entries to be added for the test (default 10)") private int entries = 10; @Parameter(names = { "-t", "--timeout" }, description = "Timeout for write/read operations in seconds (default 1)") private int timeout = 1; } @Override public boolean apply(ServerConfiguration conf, SanityFlags cmdFlags) { try { return handle(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private static boolean handle(ServerConfiguration conf, SanityFlags cmdFlags) throws Exception { try { return handleAsync(conf, cmdFlags).get(); } catch (Exception e) { LOG.warn("Error in bookie sanity test", e); return false; } } public static CompletableFuture<Boolean> handleAsync(ServerConfiguration conf, SanityFlags cmdFlags) { CompletableFuture<Boolean> result = new CompletableFuture<Boolean>(); ClientConfiguration clientConf = new ClientConfiguration(); clientConf.addConfiguration(conf); clientConf.setEnsemblePlacementPolicy(LocalBookieEnsemblePlacementPolicy.class); clientConf.setAddEntryTimeout(cmdFlags.timeout); clientConf.setReadEntryTimeout(cmdFlags.timeout); BookKeeper bk; try { bk = new BookKeeper(clientConf); } catch (BKException | IOException | InterruptedException e) { LOG.warn("Failed to initialize bookkeeper client", e); result.completeExceptionally(e); return result; } bk.asyncCreateLedger(1, 1, BookKeeper.DigestType.MAC, new byte[0], (rc, lh, ctx) -> { if (rc != BKException.Code.OK) { LOG.warn("ledger creation failed for sanity command {}", rc); result.completeExceptionally(BKException.create(rc)); return; } List<CompletableFuture<Void>> entriesFutures = new ArrayList<>(); for (int i = 0; i < cmdFlags.entries; i++) { String content = "entry-" + i; CompletableFuture<Void> entryFuture = new CompletableFuture<>(); entriesFutures.add(entryFuture); lh.asyncAddEntry(content.getBytes(UTF_8), (arc, alh, entryId, actx) -> { if (arc != BKException.Code.OK) { LOG.warn("ledger add entry failed for {}-{}", alh.getId(), arc); entryFuture.completeExceptionally(BKException.create(arc)); return; } entryFuture.complete(null); }, null); } CompletableFuture<LedgerHandle> lhFuture = new CompletableFuture<>(); CompletableFuture<Void> readEntryFuture = new CompletableFuture<>(); FutureUtils.collect(entriesFutures).thenCompose(_r -> lh.closeAsync()).thenCompose(_r -> { bk.asyncOpenLedger(lh.getId(), BookKeeper.DigestType.MAC, new byte[0], (orc, olh, octx) -> { if (orc != BKException.Code.OK) { LOG.warn("open sanity ledger failed for {}-{}", lh.getId(), orc); lhFuture.completeExceptionally(BKException.create(orc)); return; } long lac = olh.getLastAddConfirmed(); if (lac != (cmdFlags.entries - 1)) { lhFuture.completeExceptionally(new Exception("Invalid last entry found on ledger. expecting: " + (cmdFlags.entries - 1) + " -- found: " + lac)); return; } lhFuture.complete(lh); }, null); return lhFuture; }).thenCompose(rlh -> { rlh.asyncReadEntries(0, cmdFlags.entries - 1, (rrc, rlh2, entries, rctx) -> { if (rrc != BKException.Code.OK) { LOG.warn("reading sanity ledger failed for {}-{}", lh.getId(), rrc); readEntryFuture.completeExceptionally(BKException.create(rrc)); return; } int i = 0; while (entries.hasMoreElements()) { LedgerEntry entry = entries.nextElement(); String actualMsg = new String(entry.getEntry(), UTF_8); String expectedMsg = "entry-" + (i++); if (!expectedMsg.equals(actualMsg)) { readEntryFuture.completeExceptionally( new Exception("Failed validation of received message - Expected: " + expectedMsg + ", Actual: " + actualMsg)); return; } } LOG.info("Read {} entries from ledger {}", i, lh.getId()); LOG.info("Bookie sanity test succeeded"); readEntryFuture.complete(null); }, null); return readEntryFuture; }).thenAccept(_r -> { close(bk, lh); result.complete(true); }).exceptionally(ex -> { close(bk, lh); result.completeExceptionally(ex.getCause()); return null; }); }, null); return result; } public static void close(BookKeeper bk, LedgerHandle lh) { if (lh != null) { bk.asyncDeleteLedger(lh.getId(), (rc, ctx) -> { if (rc != BKException.Code.OK) { LOG.info("Failed to delete ledger id {}", lh.getId()); } close(bk); }, null); } else { close(bk); } } private static void close(BookKeeper bk) { try { bk.close(); } catch (Exception e) { LOG.info("Failed to close bookkeeper client {}", e.getMessage(), e); } } }
32
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/UpdateBookieInLedgerCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.util.concurrent.TimeUnit; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieShell; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.UpdateLedgerOp; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to update ledger command. */ public class UpdateBookieInLedgerCommand extends BookieCommand<UpdateBookieInLedgerCommand.UpdateBookieInLedgerFlags> { static final Logger LOG = LoggerFactory.getLogger(UpdateBookieInLedgerCommand.class); private static final String NAME = "update-bookie-ledger-cmd"; private static final String DESC = "Update bookie in ledgers metadata (this may take a long time)."; public UpdateBookieInLedgerCommand() { this(new UpdateBookieInLedgerFlags()); } private UpdateBookieInLedgerCommand(UpdateBookieInLedgerFlags flags) { super(CliSpec.<UpdateBookieInLedgerFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for update bookie in ledger command. */ @Accessors(fluent = true) @Setter public static class UpdateBookieInLedgerFlags extends CliFlags { @Parameter(names = { "-sb", "--srcBookie" }, description = "Source bookie which needs to be replaced by destination bookie. <bk-address:port>") private String srcBookie; @Parameter(names = { "-db", "--destBookie" }, description = "Destination bookie which replaces source bookie. <bk-address:port>") private String destBookie; @Parameter(names = { "-s", "--updatepersec" }, description = "Number of ledgers updating per second (default: 5 per sec)") private int updatePerSec = 5; @Parameter(names = { "-r", "--maxOutstandingReads" }, description = "Max outstanding reads (default: 5 * updatespersec)") private int maxOutstandingReads = updatePerSec * 5; @Parameter(names = {"-l", "--limit"}, description = "Maximum number of ledgers of ledgers to update (default: no limit)") private int limit = Integer.MIN_VALUE; @Parameter(names = { "-v", "--verbose" }, description = "Print status of the ledger updation (default: false)") private boolean verbose; @Parameter(names = { "-p", "--printprogress" }, description = "Print messages on every configured seconds if verbose turned on (default: 10 secs)") private long printProgress = 10; } @Override public boolean apply(ServerConfiguration conf, UpdateBookieInLedgerFlags cmdFlags) { try { return updateLedger(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean updateLedger(ServerConfiguration conf, UpdateBookieInLedgerFlags flags) throws InterruptedException, BKException, IOException { BookieId srcBookieAddress; BookieId destBookieAddress; try { String bookieAddress = flags.srcBookie; srcBookieAddress = BookieId.parse(bookieAddress); bookieAddress = flags.destBookie; destBookieAddress = BookieId.parse(bookieAddress); } catch (Exception e) { LOG.error("Bookie address must in <address>:<port> format"); return false; } final int rate = flags.updatePerSec; if (rate <= 0) { LOG.error("Invalid updatespersec {}, should be > 0", rate); return false; } final int maxOutstandingReads = flags.maxOutstandingReads; if (maxOutstandingReads <= 0) { LOG.error("Invalid maxOutstandingReads {}, should be > 0", maxOutstandingReads); return false; } final int limit = flags.limit; if (limit <= 0 && limit != Integer.MIN_VALUE) { LOG.error("Invalid limit {}, should be > 0", limit); return false; } final long printProgress; if (flags.verbose) { printProgress = 10; } else { printProgress = flags.printProgress; } final ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.addConfiguration(conf); final BookKeeper bk = new BookKeeper(clientConfiguration); final BookKeeperAdmin admin = new BookKeeperAdmin(bk, clientConfiguration); if (admin.getAvailableBookies().contains(srcBookieAddress) || admin.getReadOnlyBookies().contains(srcBookieAddress)) { bk.close(); admin.close(); LOG.error("Source bookie {} can't be active", srcBookieAddress); return false; } final UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, admin); BookieShell.UpdateLedgerNotifier progressable = new BookieShell.UpdateLedgerNotifier() { long lastReport = System.nanoTime(); @Override public void progress(long updated, long issued) { if (printProgress <= 0) { return; // disabled } if (TimeUnit.MILLISECONDS.toSeconds(MathUtils.elapsedMSec(lastReport)) >= printProgress) { LOG.info("Number of ledgers issued={}, updated={}", issued, updated); lastReport = MathUtils.nowInNano(); } } }; try { updateLedgerOp.updateBookieIdInLedgers(srcBookieAddress, destBookieAddress, rate, maxOutstandingReads, limit, progressable); } catch (IOException e) { LOG.error("Failed to update ledger metadata", e); return false; } return true; } }
33
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ReadLogCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import io.netty.buffer.ByteBuf; import java.io.File; import java.io.IOException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.ReadOnlyDefaultEntryLogger; import org.apache.bookkeeper.bookie.storage.EntryLogScanner; import org.apache.bookkeeper.bookie.storage.EntryLogger; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.EntryFormatter; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.apache.commons.lang.mutable.MutableBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to read entry log files. */ public class ReadLogCommand extends BookieCommand<ReadLogCommand.ReadLogFlags> { private static final String NAME = "readlog"; private static final String DESC = "Scan an entry file and format the entries into readable format."; private static final Logger LOG = LoggerFactory.getLogger(ReadLogCommand.class); private EntryLogger entryLogger; private EntryFormatter entryFormatter; private LedgerIdFormatter ledgerIdFormatter; public ReadLogCommand() { this(new ReadLogFlags()); } public ReadLogCommand(LedgerIdFormatter ledgerIdFormatter, EntryFormatter entryFormatter) { this(new ReadLogFlags()); this.ledgerIdFormatter = ledgerIdFormatter; this.entryFormatter = entryFormatter; } private ReadLogCommand(ReadLogFlags flags) { super(CliSpec.<ReadLogFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for read log command. */ @Accessors(fluent = true) @Setter public static class ReadLogFlags extends CliFlags { @Parameter(names = { "-m", "msg" }, description = "Print message body") private boolean msg; @Parameter(names = { "-l", "--ledgerid" }, description = "Ledger ID") private long ledgerId = -1; @Parameter(names = { "-e", "--entryid" }, description = "Entry ID") private long entryId = -1; @Parameter(names = { "-sp", "--startpos" }, description = "Start Position") private long startPos = -1; @Parameter(names = { "-ep", "--endpos" }, description = "End Position") private long endPos = -1; @Parameter(names = { "-f", "--filename" }, description = "Entry log filename") private String filename; @Parameter(names = { "-li", "--entrylogid" }, description = "Entry log id") private long entryLogId = -1; @Parameter(names = {"-lf", "--ledgerIdFormatter"}, description = "Set ledger id formatter") private String ledgerIdFormatter; @Parameter(names = {"-ef", "--entryformatter"}, description = "set entry formatter") private String entryFormatter; } @Override public boolean apply(ServerConfiguration conf, ReadLogFlags cmdFlags) { if (cmdFlags.ledgerIdFormatter != null && this.ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else if (this.ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } if (cmdFlags.entryFormatter != null && this.entryFormatter == null) { this.entryFormatter = EntryFormatter.newEntryFormatter(cmdFlags.entryFormatter, conf); } else if (this.entryFormatter == null) { this.entryFormatter = EntryFormatter.newEntryFormatter(conf); } if (cmdFlags.entryLogId == -1 && cmdFlags.filename == null) { LOG.error("Missing entry log id or entry log file name"); usage(); return false; } try { return readLog(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean readLog(ServerConfiguration conf, ReadLogFlags flags) throws Exception { long logId = flags.entryLogId; if (logId == -1 && flags.filename != null) { File f = new File(flags.filename); String name = f.getName(); if (!name.endsWith(".log")) { LOG.error("Invalid entry log file name {}", flags.filename); usage(); return false; } String idString = name.split("\\.")[0]; logId = Long.parseLong(idString, 16); } final long lId = flags.ledgerId; final long eId = flags.entryId; final long startpos = flags.startPos; final long endpos = flags.endPos; // scan entry log if (startpos != -1) { if ((endpos != -1) && (endpos < startpos)) { LOG.error("ERROR: StartPosition of the range should be lesser than or equal to EndPosition"); return false; } scanEntryLogForPositionRange(conf, logId, startpos, endpos, flags.msg); } else if (lId != -1) { scanEntryLogForSpecificEntry(conf, logId, lId, eId, flags.msg); } else { scanEntryLog(conf, logId, flags.msg); } return true; } /** * Scan over an entry log file for entries in the given position range. * * @param logId Entry Log File id. * @param rangeStartPos Start position of the entry we are looking for * @param rangeEndPos End position of the entry we are looking for (-1 for till the end of the entrylog) * @param printMsg Whether printing the entry data. * @throws Exception */ private void scanEntryLogForPositionRange(ServerConfiguration conf, long logId, final long rangeStartPos, final long rangeEndPos, final boolean printMsg) throws Exception { LOG.info("Scan entry log {} ({}.log) for PositionRange: {} - {}", logId, Long.toHexString(logId), rangeStartPos, rangeEndPos); final MutableBoolean entryFound = new MutableBoolean(false); scanEntryLog(conf, logId, new EntryLogScanner() { private MutableBoolean stopScanning = new MutableBoolean(false); @Override public boolean accept(long ledgerId) { return !stopScanning.booleanValue(); } @Override public void process(long ledgerId, long entryStartPos, ByteBuf entry) throws IOException { if (!stopScanning.booleanValue()) { if ((rangeEndPos != -1) && (entryStartPos > rangeEndPos)) { stopScanning.setValue(true); } else { int entrySize = entry.readableBytes(); /** * entrySize of an entry (inclusive of payload and * header) value is stored as int value in log file, but * it is not counted in the entrySize, hence for calculating * the end position of the entry we need to add additional * 4 (intsize of entrySize). Please check * EntryLogger.scanEntryLog. */ long entryEndPos = entryStartPos + entrySize + 4 - 1; if (((rangeEndPos == -1) || (entryStartPos <= rangeEndPos)) && (rangeStartPos <= entryEndPos)) { FormatUtil.formatEntry(entryStartPos, entry, printMsg, ledgerIdFormatter, entryFormatter); entryFound.setValue(true); } } } } }); if (!entryFound.booleanValue()) { LOG.info("Entry log {} ({}.log) doesn't has any entry in the range {} - {}. " + "Probably the position range, you have provided is lesser than the LOGFILE_HEADER_SIZE (1024) " + "or greater than the current log filesize.", logId, Long.toHexString(logId), rangeStartPos, rangeEndPos); } } /** * Scan over entry log. * * @param logId Entry Log Id * @param scanner Entry Log Scanner */ private void scanEntryLog(ServerConfiguration conf, long logId, EntryLogScanner scanner) throws IOException { initEntryLogger(conf); entryLogger.scanEntryLog(logId, scanner); } private synchronized void initEntryLogger(ServerConfiguration conf) throws IOException { if (null == entryLogger) { // provide read only entry logger entryLogger = new ReadOnlyDefaultEntryLogger(conf); } } /** * Scan over an entry log file for a particular entry. * * @param logId Entry Log File id. * @param ledgerId id of the ledger * @param entryId entryId of the ledger we are looking for (-1 for all of the entries of the ledger) * @param printMsg Whether printing the entry data. * @throws Exception */ private void scanEntryLogForSpecificEntry(ServerConfiguration conf, long logId, final long ledgerId, final long entryId, final boolean printMsg) throws Exception { LOG.info("Scan entry log {} ({}.log) for LedgerId {} {}", logId, Long.toHexString(logId), ledgerId, ((entryId == -1) ? "" : " for EntryId " + entryId)); final MutableBoolean entryFound = new MutableBoolean(false); scanEntryLog(conf, logId, new EntryLogScanner() { @Override public boolean accept(long candidateLedgerId) { return ((candidateLedgerId == ledgerId) && ((!entryFound.booleanValue()) || (entryId == -1))); } @Override public void process(long candidateLedgerId, long startPos, ByteBuf entry) { long entrysLedgerId = entry.getLong(entry.readerIndex()); long entrysEntryId = entry.getLong(entry.readerIndex() + 8); if ((candidateLedgerId == entrysLedgerId) && (candidateLedgerId == ledgerId) && ((entrysEntryId == entryId) || (entryId == -1))) { entryFound.setValue(true); FormatUtil.formatEntry(startPos, entry, printMsg, ledgerIdFormatter, entryFormatter); } } }); if (!entryFound.booleanValue()) { LOG.info("LedgerId {} {} is not available in the entry log {} ({}.log)", ledgerId, ((entryId == -1) ? "" : " EntryId " + entryId), logId, Long.toHexString(logId)); } } /** * Scan over an entry log file. * * @param logId * Entry Log File id. * @param printMsg * Whether printing the entry data. */ private void scanEntryLog(ServerConfiguration conf, long logId, final boolean printMsg) throws Exception { LOG.info("Scan entry log {} ({}.log)", logId, Long.toHexString(logId)); scanEntryLog(conf, logId, new EntryLogScanner() { @Override public boolean accept(long ledgerId) { return true; } @Override public void process(long ledgerId, long startPos, ByteBuf entry) { FormatUtil.formatEntry(startPos, entry, printMsg, ledgerIdFormatter, entryFormatter); } }); } }
34
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/FormatCommand.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.tools.cli.commands.bookie; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithRegistrationManager; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.util.concurrent.ExecutionException; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.Cookie; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.versioning.Versioned; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to format the current server contents. */ public class FormatCommand extends BookieCommand<FormatCommand.Flags> { static final Logger LOG = LoggerFactory.getLogger(FormatCommand.class); private static final String NAME = "format"; private static final String DESC = "Format the current server contents."; public FormatCommand() { this(new Flags()); } public FormatCommand(Flags flags) { super(CliSpec.<Flags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for format bookie command. */ @Accessors(fluent = true) @Setter public static class Flags extends CliFlags { @Parameter(names = {"-n", "--noninteractive"}, description = "Whether to confirm if old data exists?") private boolean nonInteractive; @Parameter(names = {"-f", "--force"}, description = "If [noninteractive] is specified, then whether" + "to force delete the old data without prompt?") private boolean force; @Parameter(names = {"-d", "--deletecookie"}, description = "Delete its cookie on metadata store.") private boolean deleteCookie; } @Override public boolean apply(ServerConfiguration conf, Flags cmdFlags) { ServerConfiguration bfconf = new ServerConfiguration(conf); boolean result = BookieImpl.format(bfconf, cmdFlags.nonInteractive, cmdFlags.force); // delete cookie if (cmdFlags.deleteCookie) { try { runFunctionWithRegistrationManager(conf, rm -> { try { Versioned<Cookie> cookie = Cookie.readFromRegistrationManager(rm, bfconf); cookie.getValue().deleteFromRegistrationManager(rm, bfconf, cookie.getVersion()); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } return null; }); } catch (MetadataException | ExecutionException e) { throw new UncheckedExecutionException(e.getMessage(), e); } } return result; } }
35
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/FormatUtil.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.tools.cli.commands.bookie; import io.netty.buffer.ByteBuf; import java.util.Formatter; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.util.EntryFormatter; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * .Provide to format message. */ public class FormatUtil { private static final Logger LOG = LoggerFactory.getLogger(FormatUtil.class); /** * Format the message into a readable format. * @param pos * File offset of the message stored in entry log file * @param recBuff * Entry Data * @param printMsg * Whether printing the message body * @param ledgerIdFormatter * @param entryFormatter */ public static void formatEntry(long pos, ByteBuf recBuff, boolean printMsg, LedgerIdFormatter ledgerIdFormatter, EntryFormatter entryFormatter) { int entrySize = recBuff.readableBytes(); long ledgerId = recBuff.readLong(); long entryId = recBuff.readLong(); LOG.info("--------- Lid={}, Eid={}, ByteOffset={}, EntrySize={} ---------", ledgerIdFormatter.formatLedgerId(ledgerId), entryId, pos, entrySize); if (entryId == BookieImpl.METAENTRY_ID_LEDGER_KEY) { int masterKeyLen = recBuff.readInt(); byte[] masterKey = new byte[masterKeyLen]; recBuff.readBytes(masterKey); LOG.info("Type: META"); LOG.info("MasterKey: {}", bytes2Hex(masterKey)); LOG.info(""); return; } if (entryId == BookieImpl.METAENTRY_ID_FENCE_KEY) { LOG.info("Type: META"); LOG.info("Fenced"); LOG.info(""); return; } // process a data entry long lastAddConfirmed = recBuff.readLong(); LOG.info("Type: DATA"); LOG.info("LastConfirmed: {}", lastAddConfirmed); if (!printMsg) { LOG.info(""); return; } // skip digest checking recBuff.skipBytes(8); LOG.info("Data:"); LOG.info(""); try { byte[] ret = new byte[recBuff.readableBytes()]; recBuff.readBytes(ret); entryFormatter.formatEntry(ret); } catch (Exception e) { LOG.info("N/A. Corrupted."); } LOG.info(""); } public static String bytes2Hex(byte[] data) { StringBuilder sb = new StringBuilder(data.length * 2); Formatter formatter = new Formatter(sb); for (byte b : data) { formatter.format("%02x", b); } formatter.close(); return sb.toString(); } }
36
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ListActiveLedgersCommand.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.tools.cli.commands.bookie; import static org.apache.bookkeeper.meta.MetadataDrivers.runFunctionWithLedgerManagerFactory; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.DefaultEntryLogger; import org.apache.bookkeeper.bookie.EntryLogMetadata; import org.apache.bookkeeper.bookie.ReadOnlyDefaultEntryLogger; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.LedgerManager; import org.apache.bookkeeper.meta.exceptions.MetadataException; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks; import org.apache.bookkeeper.tools.cli.commands.bookie.ListActiveLedgersCommand.ActiveLedgerFlags; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.apache.zookeeper.AsyncCallback.VoidCallback; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * List active(exist in metadata storage) ledgers in a entry log file. * **/ @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") public class ListActiveLedgersCommand extends BookieCommand<ActiveLedgerFlags>{ private static final Logger LOG = LoggerFactory.getLogger(ListActiveLedgersCommand.class); private static final String NAME = "active ledger"; private static final String DESC = "Retrieve bookie active ledger info."; private static final long DEFAULT_TIME_OUT = 1000; private static final long DEFAULT_LOG_ID = 0; private static final String DEFAULT_LEDGER_ID_FORMATTER = ""; private LedgerIdFormatter ledgerIdFormatter; public ListActiveLedgersCommand(){ this(new ActiveLedgerFlags()); } public ListActiveLedgersCommand(LedgerIdFormatter ledgerIdFormatter){ this(new ActiveLedgerFlags()); this.ledgerIdFormatter = ledgerIdFormatter; } public ListActiveLedgersCommand(ActiveLedgerFlags ledgerFlags){ super(CliSpec.<ActiveLedgerFlags>newBuilder(). withName(NAME). withDescription(DESC). withFlags(ledgerFlags). build()); } /** * Flags for active ledger command. */ @Accessors(fluent = true) @Setter public static class ActiveLedgerFlags extends CliFlags { @Parameter(names = { "-l", "--logid" }, description = "Entry log file id") private long logId = DEFAULT_LOG_ID; @Parameter(names = { "-t", "--timeout" }, description = "Read timeout(ms)") private long timeout = DEFAULT_TIME_OUT; @Parameter(names = { "-f", "--ledgerIdFormatter" }, description = "Ledger id formatter") private String ledgerIdFormatter = DEFAULT_LEDGER_ID_FORMATTER; } @Override public boolean apply(ServerConfiguration bkConf, ActiveLedgerFlags cmdFlags){ initLedgerFormatter(bkConf, cmdFlags); try { handler(bkConf, cmdFlags); } catch (MetadataException | ExecutionException e) { throw new UncheckedExecutionException(e.getMessage(), e); } return true; } private void initLedgerFormatter(ServerConfiguration conf, ActiveLedgerFlags cmdFlags) { if (!cmdFlags.ledgerIdFormatter.equals(DEFAULT_LEDGER_ID_FORMATTER)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else if (ledgerIdFormatter == null){ this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } } public void handler(ServerConfiguration bkConf, ActiveLedgerFlags cmdFlags) throws ExecutionException, MetadataException { runFunctionWithLedgerManagerFactory(bkConf, mFactory -> { try (LedgerManager ledgerManager = mFactory.newLedgerManager()) { Set<Long> activeLedgersOnMetadata = new HashSet<Long>(); BookkeeperInternalCallbacks.Processor<Long> ledgerProcessor = (ledger, cb)->{ activeLedgersOnMetadata.add(ledger); cb.processResult(BKException.Code.OK, null, null); }; CountDownLatch done = new CountDownLatch(1); AtomicInteger resultCode = new AtomicInteger(BKException.Code.OK); VoidCallback endCallback = (rs, s, obj)->{ resultCode.set(rs); done.countDown(); }; ledgerManager.asyncProcessLedgers(ledgerProcessor, endCallback, null, BKException.Code.OK, BKException.Code.ReadException); if (done.await(cmdFlags.timeout, TimeUnit.MILLISECONDS)){ if (resultCode.get() == BKException.Code.OK) { DefaultEntryLogger entryLogger = new ReadOnlyDefaultEntryLogger(bkConf); EntryLogMetadata entryLogMetadata = entryLogger.getEntryLogMetadata(cmdFlags.logId); List<Long> ledgersOnEntryLog = entryLogMetadata.getLedgersMap().keys(); if (ledgersOnEntryLog.size() == 0) { LOG.info("Ledgers on log file {} is empty", cmdFlags.logId); } List<Long> activeLedgersOnEntryLog = new ArrayList<Long>(ledgersOnEntryLog.size()); for (long ledger : ledgersOnEntryLog) { if (activeLedgersOnMetadata.contains(ledger)) { activeLedgersOnEntryLog.add(ledger); } } printActiveLedgerOnEntryLog(cmdFlags.logId, activeLedgersOnEntryLog); } else { LOG.info("Read active ledgers id from metadata store,fail code {}", resultCode.get()); throw BKException.create(resultCode.get()); } } else { LOG.info("Read active ledgers id from metadata store timeout"); } } catch (BKException | InterruptedException | IOException e){ LOG.error("Received Exception while processing ledgers", e); throw new UncheckedExecutionException(e); } return null; }); } public void printActiveLedgerOnEntryLog(long logId, List<Long> activeLedgers){ if (activeLedgers.size() == 0){ LOG.info("No active ledgers on log file {}", logId); } else { LOG.info("Active ledgers on entry log {} as follow:", logId); } Collections.sort(activeLedgers); for (long a : activeLedgers){ LOG.info("{} ", ledgerIdFormatter.formatLedgerId(a)); } } }
37
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/FlipBookieIdCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import java.io.IOException; import java.util.concurrent.TimeUnit; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.BookieShell; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeper; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.UpdateLedgerOp; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to update ledger command. */ public class FlipBookieIdCommand extends BookieCommand<FlipBookieIdCommand.FlipBookieIdFlags> { static final Logger LOG = LoggerFactory.getLogger(FlipBookieIdCommand.class); private static final String NAME = "flip-bookie-id"; private static final String DESC = "Update bookie id in ledgers (this may take a long time)."; public FlipBookieIdCommand() { this(new FlipBookieIdFlags()); } private FlipBookieIdCommand(FlipBookieIdFlags flags) { super(CliSpec.<FlipBookieIdFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for update ledger command. */ @Accessors(fluent = true) @Setter public static class FlipBookieIdFlags extends CliFlags { @Parameter(names = { "-host", "--hostname" }, description = "Expects configuration useHostNameAsBookieID=true as the option value (default: ip address)") private boolean hostname; @Parameter(names = { "-s", "--updatepersec" }, description = "Number of ledgers updating per second (default: 5 per sec)") private int updatePerSec = 5; @Parameter(names = { "-r", "--maxOutstandingReads" }, description = "Max outstanding reads (default: 5 * updatespersec)") private int maxOutstandingReads = updatePerSec * 5; @Parameter(names = {"-l", "--limit"}, description = "Maximum number of ledgers of ledgers to update (default: no limit)") private int limit = Integer.MIN_VALUE; @Parameter(names = { "-v", "--verbose" }, description = "Print status of the ledger updation (default: false)") private boolean verbose; @Parameter(names = { "-p", "--printprogress" }, description = "Print messages on every configured seconds if verbose turned on (default: 10 secs)") private long printProgress = 10; } @Override public boolean apply(ServerConfiguration conf, FlipBookieIdFlags cmdFlags) { try { return updateLedger(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean updateLedger(ServerConfiguration conf, FlipBookieIdFlags flags) throws InterruptedException, BKException, IOException { if (!conf.getUseHostNameAsBookieID() && flags.hostname) { LOG.error("Expects configuration useHostNameAsBookieID=true as the option value"); return false; } else if (conf.getUseHostNameAsBookieID() && !flags.hostname) { LOG.error("Expects configuration useHostNameAsBookieID=false as the option value'"); return false; } final int rate = flags.updatePerSec; if (rate <= 0) { LOG.error("Invalid updatespersec {}, should be > 0", rate); return false; } final int maxOutstandingReads = flags.maxOutstandingReads; if (maxOutstandingReads <= 0) { LOG.error("Invalid maxOutstandingReads {}, should be > 0", maxOutstandingReads); return false; } final int limit = flags.limit; if (limit <= 0 && limit != Integer.MIN_VALUE) { LOG.error("Invalid limit {}, should be > 0", limit); return false; } final long printProgress; if (flags.verbose) { printProgress = 10; } else { printProgress = flags.printProgress; } final ClientConfiguration clientConfiguration = new ClientConfiguration(); clientConfiguration.addConfiguration(conf); final BookKeeper bk = new BookKeeper(clientConfiguration); final BookKeeperAdmin admin = new BookKeeperAdmin(bk); final UpdateLedgerOp updateLedgerOp = new UpdateLedgerOp(bk, admin); final ServerConfiguration serverConfiguration = new ServerConfiguration(conf); final BookieId newBookieId = BookieImpl.getBookieId(serverConfiguration); serverConfiguration.setUseHostNameAsBookieID(!flags.hostname); final BookieId oldBookieId = BookieImpl.getBookieId(serverConfiguration); BookieShell.UpdateLedgerNotifier progressable = new BookieShell.UpdateLedgerNotifier() { long lastReport = System.nanoTime(); @Override public void progress(long updated, long issued) { if (printProgress <= 0) { return; // disabled } if (TimeUnit.MILLISECONDS.toSeconds(MathUtils.elapsedMSec(lastReport)) >= printProgress) { LOG.info("Number of ledgers issued={}, updated={}", issued, updated); lastReport = MathUtils.nowInNano(); } } }; try { updateLedgerOp.updateBookieIdInLedgers(oldBookieId, newBookieId, rate, maxOutstandingReads, limit, progressable); } catch (IOException e) { LOG.error("Failed to update ledger metadata", e); return false; } return true; } }
38
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ConvertToInterleavedStorageCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import io.netty.buffer.PooledByteBufAllocator; import java.nio.file.FileSystems; import java.nio.file.Files; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieResources; import org.apache.bookkeeper.bookie.CheckpointSource; import org.apache.bookkeeper.bookie.Checkpointer; import org.apache.bookkeeper.bookie.InterleavedLedgerStorage; import org.apache.bookkeeper.bookie.LedgerCache; import org.apache.bookkeeper.bookie.LedgerDirsManager; import org.apache.bookkeeper.bookie.storage.ldb.DbLedgerStorage; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.DiskChecker; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A command to convert bookie indexes from DbLedgerStorage to InterleavedStorage format. */ public class ConvertToInterleavedStorageCommand extends BookieCommand<ConvertToInterleavedStorageCommand.CTISFlags> { private static final Logger LOG = LoggerFactory.getLogger(ConvertToInterleavedStorageCommand.class); private static final String NAME = "converttointerleavedstorage"; private static final String DESC = "Convert bookie indexes from DbLedgerStorage to InterleavedStorage format"; private static final String NOT_INIT = "default formatter"; @Setter private LedgerIdFormatter ledgerIdFormatter; public ConvertToInterleavedStorageCommand() { this(new CTISFlags()); } public ConvertToInterleavedStorageCommand(CTISFlags flags) { super(CliSpec.<CTISFlags>newBuilder().withName(NAME).withDescription(DESC).withFlags(flags).build()); } /** * Flags for this command. */ @Accessors(fluent = true) public static class CTISFlags extends CliFlags{ @Parameter(names = { "-l", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter = NOT_INIT; } @Override public boolean apply(ServerConfiguration conf, CTISFlags cmdFlags) { initLedgerIdFormatter(conf, cmdFlags); try { return handle(conf); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } private boolean handle(ServerConfiguration bkConf) throws Exception { LOG.info("=== Converting DbLedgerStorage ==="); ServerConfiguration conf = new ServerConfiguration(bkConf); DiskChecker diskChecker = new DiskChecker(bkConf.getDiskUsageThreshold(), bkConf.getDiskUsageWarnThreshold()); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(bkConf, bkConf.getLedgerDirs(), diskChecker); LedgerDirsManager indexDirsManager = BookieResources.createIndexDirsManager( conf, diskChecker, NullStatsLogger.INSTANCE, ledgerDirsManager); DbLedgerStorage dbStorage = new DbLedgerStorage(); InterleavedLedgerStorage interleavedStorage = new InterleavedLedgerStorage(); CheckpointSource checkpointSource = new CheckpointSource() { @Override public Checkpoint newCheckpoint() { return Checkpoint.MAX; } @Override public void checkpointComplete(Checkpoint checkpoint, boolean compact) {} }; Checkpointer checkpointer = new Checkpointer() { @Override public void startCheckpoint(CheckpointSource.Checkpoint checkpoint) { // No-op } @Override public void start() { // no-op } }; dbStorage.initialize(conf, null, ledgerDirsManager, indexDirsManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT); dbStorage.setCheckpointSource(checkpointSource); dbStorage.setCheckpointer(checkpointer); interleavedStorage.initialize(conf, null, ledgerDirsManager, indexDirsManager, NullStatsLogger.INSTANCE, PooledByteBufAllocator.DEFAULT); interleavedStorage.setCheckpointSource(checkpointSource); interleavedStorage.setCheckpointer(checkpointer); LedgerCache interleavedLedgerCache = interleavedStorage.getLedgerCache(); int convertedLedgers = 0; for (long ledgerId : dbStorage.getActiveLedgersInRange(0, Long.MAX_VALUE)) { if (LOG.isDebugEnabled()) { LOG.debug("Converting ledger {}", ledgerIdFormatter.formatLedgerId(ledgerId)); } interleavedStorage.setMasterKey(ledgerId, dbStorage.readMasterKey(ledgerId)); if (dbStorage.isFenced(ledgerId)) { interleavedStorage.setFenced(ledgerId); } long lastEntryInLedger = dbStorage.getLastEntryInLedger(ledgerId); for (long entryId = 0; entryId <= lastEntryInLedger; entryId++) { try { long location = dbStorage.getLocation(ledgerId, entryId); if (location != 0L) { interleavedLedgerCache.putEntryOffset(ledgerId, entryId, location); } } catch (Bookie.NoEntryException e) { // Ignore entry } } if (++convertedLedgers % 1000 == 0) { LOG.info("Converted {} ledgers", convertedLedgers); } } dbStorage.shutdown(); interleavedLedgerCache.flushLedger(true); interleavedStorage.flush(); interleavedStorage.shutdown(); String baseDir = ledgerDirsManager.getAllLedgerDirs().get(0).toString(); // Rename databases and keep backup Files.move(FileSystems.getDefault().getPath(baseDir, "ledgers"), FileSystems.getDefault().getPath(baseDir, "ledgers.backup")); Files.move(FileSystems.getDefault().getPath(baseDir, "locations"), FileSystems.getDefault().getPath(baseDir, "locations.backup")); LOG.info("---- Done Converting {} ledgers ----", convertedLedgers); return true; } private void initLedgerIdFormatter(ServerConfiguration conf, CTISFlags flags) { if (this.ledgerIdFormatter != null) { return; } if (flags.ledgerIdFormatter.equals(NOT_INIT)) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } else { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(flags.ledgerIdFormatter, conf); } } }
39
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/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. */ /** * Commands to operate a single bookie. */ package org.apache.bookkeeper.tools.cli.commands.bookie;
40
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/commands/bookie/ReadLedgerCommand.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.tools.cli.commands.bookie; import com.beust.jcommander.Parameter; import com.google.common.util.concurrent.UncheckedExecutionException; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.util.Iterator; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.stream.LongStream; import lombok.Setter; import lombok.experimental.Accessors; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperAdmin; import org.apache.bookkeeper.client.LedgerEntry; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookieClient; import org.apache.bookkeeper.proto.BookieClientImpl; import org.apache.bookkeeper.proto.BookieProtocol; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.tools.cli.helpers.BookieCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.bookkeeper.util.EntryFormatter; import org.apache.bookkeeper.util.LedgerIdFormatter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Command to read ledger entries. */ public class ReadLedgerCommand extends BookieCommand<ReadLedgerCommand.ReadLedgerFlags> { private static final Logger LOG = LoggerFactory.getLogger(ReadLedgerCommand.class); private static final String NAME = "readledger"; private static final String DESC = "Read a range of entries from a ledger."; EntryFormatter entryFormatter; LedgerIdFormatter ledgerIdFormatter; public ReadLedgerCommand() { this(new ReadLedgerFlags()); } public ReadLedgerCommand(EntryFormatter entryFormatter, LedgerIdFormatter ledgerIdFormatter) { this(new ReadLedgerFlags()); this.ledgerIdFormatter = ledgerIdFormatter; this.entryFormatter = entryFormatter; } private ReadLedgerCommand(ReadLedgerFlags flags) { super(CliSpec.<ReadLedgerFlags>newBuilder() .withName(NAME) .withDescription(DESC) .withFlags(flags) .build()); } /** * Flags for read ledger command. */ @Accessors(fluent = true) @Setter public static class ReadLedgerFlags extends CliFlags { @Parameter(names = { "-m", "--msg" }, description = "Print message body") private boolean msg; @Parameter(names = { "-l", "--ledgerid" }, description = "Ledger ID") private long ledgerId = -1; @Parameter(names = { "-fe", "--firstentryid" }, description = "First Entry ID") private long firstEntryId = -1; @Parameter(names = { "-le", "--lastentryid" }, description = "Last Entry ID") private long lastEntryId = -1; @Parameter(names = { "-r", "--force-recovery" }, description = "Ensure the ledger is properly closed before reading") private boolean forceRecovery; @Parameter(names = { "-b", "--bookie" }, description = "Only read from a specific bookie") private String bookieAddresss; @Parameter(names = { "-lf", "--ledgeridformatter" }, description = "Set ledger id formatter") private String ledgerIdFormatter; @Parameter(names = { "-ef", "--entryformatter" }, description = "Set entry formatter") private String entryFormatter; } @Override public boolean apply(ServerConfiguration conf, ReadLedgerFlags cmdFlags) { if (cmdFlags.ledgerIdFormatter != null && ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(cmdFlags.ledgerIdFormatter, conf); } else if (ledgerIdFormatter == null) { this.ledgerIdFormatter = LedgerIdFormatter.newLedgerIdFormatter(conf); } if (cmdFlags.entryFormatter != null && entryFormatter == null) { this.entryFormatter = EntryFormatter.newEntryFormatter(cmdFlags.entryFormatter, conf); } else if (entryFormatter == null) { this.entryFormatter = EntryFormatter.newEntryFormatter(conf); } try { return readledger(conf, cmdFlags); } catch (Exception e) { throw new UncheckedExecutionException(e.getMessage(), e); } } @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") private boolean readledger(ServerConfiguration serverConf, ReadLedgerFlags flags) throws InterruptedException, BKException, IOException { long lastEntry = flags.lastEntryId; final BookieId bookie; if (flags.bookieAddresss != null) { // A particular bookie was specified bookie = BookieId.parse(flags.bookieAddresss); } else { bookie = null; } ClientConfiguration conf = new ClientConfiguration(); conf.addConfiguration(serverConf); try (BookKeeperAdmin bk = new BookKeeperAdmin(conf)) { if (flags.forceRecovery) { // Force the opening of the ledger to trigger recovery try (LedgerHandle lh = bk.openLedger(flags.ledgerId)) { if (lastEntry == -1 || lastEntry > lh.getLastAddConfirmed()) { lastEntry = lh.getLastAddConfirmed(); } } } if (bookie == null) { // No bookie was specified, use normal bk client Iterator<LedgerEntry> entries = bk.readEntries(flags.ledgerId, flags.firstEntryId, lastEntry) .iterator(); while (entries.hasNext()) { LedgerEntry entry = entries.next(); formatEntry(entry, flags.msg); } } else { // Use BookieClient to target a specific bookie EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); OrderedExecutor executor = OrderedExecutor.newBuilder() .numThreads(1) .name("BookieClientScheduler") .build(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( new DefaultThreadFactory("BookKeeperClientSchedulerPool")); BookieClient bookieClient = new BookieClientImpl(conf, eventLoopGroup, UnpooledByteBufAllocator.DEFAULT, executor, scheduler, NullStatsLogger.INSTANCE, bk.getBookieAddressResolver()); LongStream.range(flags.firstEntryId, lastEntry).forEach(entryId -> { CompletableFuture<Void> future = new CompletableFuture<>(); bookieClient.readEntry(bookie, flags.ledgerId, entryId, (rc, ledgerId1, entryId1, buffer, ctx) -> { if (rc != BKException.Code.OK) { LOG.error("Failed to read entry {} -- {}", entryId1, BKException.getMessage(rc)); future.completeExceptionally(BKException.create(rc)); return; } LOG.info("--------- Lid={}, Eid={} ---------", ledgerIdFormatter.formatLedgerId(flags.ledgerId), entryId); if (flags.msg) { LOG.info("Data: " + ByteBufUtil.prettyHexDump(buffer)); } future.complete(null); }, null, BookieProtocol.FLAG_NONE); try { future.get(); } catch (Exception e) { LOG.error("Error future.get while reading entries from ledger {}", flags.ledgerId, e); } }); eventLoopGroup.shutdownGracefully(); executor.shutdown(); bookieClient.close(); } } return true; } /** * Format the entry into a readable format. * * @param entry * ledgerentry to print * @param printMsg * Whether printing the message body */ private void formatEntry(LedgerEntry entry, boolean printMsg) { long ledgerId = entry.getLedgerId(); long entryId = entry.getEntryId(); long entrySize = entry.getLength(); LOG.info("--------- Lid={}, Eid={}, EntrySize={} ---------", ledgerIdFormatter.formatLedgerId(ledgerId), entryId, entrySize); if (printMsg) { entryFormatter.formatEntry(entry.getEntry()); } } }
41
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/DiscoveryCommand.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.tools.cli.helpers; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.net.URI; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import lombok.Cleanup; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.client.api.BookKeeper; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.discover.RegistrationClient; import org.apache.bookkeeper.meta.MetadataClientDriver; import org.apache.bookkeeper.meta.MetadataDrivers; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; /** * This is a mixin for commands that talks to discovery service. */ @Slf4j public abstract class DiscoveryCommand<DiscoveryFlagsT extends CliFlags> extends ClientCommand<DiscoveryFlagsT> { protected DiscoveryCommand(CliSpec<DiscoveryFlagsT> spec) { super(spec); } @Override @SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") protected boolean apply(ClientConfiguration clientConf, DiscoveryFlagsT cmdFlags) { try { URI metadataServiceUri = URI.create(clientConf.getMetadataServiceUri()); @Cleanup("shutdown") ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(); try (MetadataClientDriver driver = MetadataDrivers.getClientDriver(metadataServiceUri)) { driver.initialize( clientConf, executor, NullStatsLogger.INSTANCE, Optional.empty()); run(driver.getRegistrationClient(), cmdFlags, clientConf.getBookieAddressResolverEnabled()); return true; } } catch (Exception e) { log.error("Fail to process command '{}'", name(), e); return false; } } @Override protected void run(BookKeeper bk, DiscoveryFlagsT cmdFlags) throws Exception { throw new IllegalStateException("It should never be called."); } protected abstract void run(RegistrationClient regClient, DiscoveryFlagsT cmdFlags, boolean bookieAddressResolverEnabled) throws Exception; }
42
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/BookieCommand.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.tools.cli.helpers; import org.apache.bookkeeper.common.net.ServiceURI; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.common.BKCommand; import org.apache.bookkeeper.tools.common.BKFlags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.commons.configuration.CompositeConfiguration; /** * This is a mixin for bookie related commands to extends. */ public abstract class BookieCommand<BookieFlagsT extends CliFlags> extends BKCommand<BookieFlagsT> { protected BookieCommand(CliSpec<BookieFlagsT> spec) { super(spec); } @Override protected boolean apply(ServiceURI serviceURI, CompositeConfiguration conf, BKFlags globalFlags, BookieFlagsT cmdFlags) { ServerConfiguration serverConf = new ServerConfiguration(); serverConf.loadConf(conf); if (null != serviceURI) { serverConf.setMetadataServiceUri(serviceURI.getUri().toString()); } return apply(serverConf, cmdFlags); } public abstract boolean apply(ServerConfiguration conf, BookieFlagsT cmdFlags); }
43
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/CommandHelpers.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.tools.cli.helpers; import com.google.common.net.InetAddresses; import java.net.InetAddress; import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.BookieAddressResolver; /** * Helper classes used by the cli commands. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class CommandHelpers { private static final String UNKNOWN = "UNKNOWN"; /* * The string returned is of the form: * BookieID:bookieId, IP:ip, Port: port, Hostname: hostname * When using hostname as bookie id, it's possible that the host is no longer valid and * can't get a ip from the hostname, so using UNKNOWN to indicate ip is unknown for the hostname */ public static String getBookieSocketAddrStringRepresentation(BookieId bookieId, BookieAddressResolver bookieAddressResolver) { try { BookieSocketAddress networkAddress = bookieAddressResolver.resolve(bookieId); String hostname = networkAddress.getHostName(); String realHostname; String ip; if (InetAddresses.isInetAddress(hostname)){ ip = hostname; realHostname = networkAddress.getSocketAddress().getAddress().getCanonicalHostName(); } else { InetAddress ia = networkAddress.getSocketAddress().getAddress(); if (null != ia){ ip = ia.getHostAddress(); } else { ip = UNKNOWN; } realHostname = hostname; } return formatBookieSocketAddress(bookieId, ip, networkAddress.getPort(), realHostname); } catch (BookieAddressResolver.BookieIdNotResolvedException bookieNotAvailable) { return formatBookieSocketAddress(bookieId, UNKNOWN, 0, UNKNOWN); } } /** * Format {@link BookieSocketAddress}. **/ private static String formatBookieSocketAddress(BookieId bookieId, String ip, int port, String hostName) { return String.format("BookieID:%s, IP:%s, Port:%d, Hostname:%s", bookieId.toString(), ip, port, hostName); } }
44
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/ClientCommand.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.tools.cli.helpers; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.client.api.BookKeeper; import org.apache.bookkeeper.common.net.ServiceURI; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.tools.common.BKCommand; import org.apache.bookkeeper.tools.common.BKFlags; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.bookkeeper.tools.framework.CliSpec; import org.apache.commons.configuration.CompositeConfiguration; /** * This is a mixin class for commands that needs a bookkeeper client. */ @Slf4j public abstract class ClientCommand<ClientFlagsT extends CliFlags> extends BKCommand<ClientFlagsT> { protected ClientCommand(CliSpec<ClientFlagsT> spec) { super(spec); } @Override protected boolean apply(ServiceURI serviceURI, CompositeConfiguration conf, BKFlags globalFlags, ClientFlagsT cmdFlags) { ClientConfiguration clientConf = new ClientConfiguration(); clientConf.loadConf(conf); if (null != serviceURI) { clientConf.setMetadataServiceUri(serviceURI.getUri().toString()); } return apply(clientConf, cmdFlags); } public boolean apply(ServerConfiguration conf, ClientFlagsT cmdFlags) { ClientConfiguration clientConf = new ClientConfiguration(conf); return apply(clientConf, cmdFlags); } protected boolean apply(ClientConfiguration conf, ClientFlagsT cmdFlags) { try (BookKeeper bk = BookKeeper.newBuilder(conf).build()) { run(bk, cmdFlags); return true; } catch (Exception e) { log.error("Failed to process command '{}'", name(), e); return false; } } protected abstract void run(BookKeeper bk, ClientFlagsT cmdFlags) throws Exception; }
45
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/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. */ /** * This classes provides some helper mixins for easily to add commands * to bookie shell. */ package org.apache.bookkeeper.tools.cli.helpers;
46
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/tools/cli/helpers/BookieShellCommand.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.tools.cli.helpers; import org.apache.bookkeeper.bookie.BookieShell.Command; import org.apache.bookkeeper.tools.common.BKCommand; import org.apache.bookkeeper.tools.framework.CliFlags; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.lang3.StringUtils; /** * This is a util class that converts new cli command to old shell command. */ public class BookieShellCommand<CliFlagsT extends CliFlags> implements Command { protected final String shellCmdName; protected final BKCommand<CliFlagsT> bkCmd; protected final CompositeConfiguration conf; public BookieShellCommand(String shellCmdName, BKCommand<CliFlagsT> bkCmd, CompositeConfiguration conf) { this.shellCmdName = shellCmdName; this.bkCmd = bkCmd; this.conf = conf; } @Override public int runCmd(String[] args) throws Exception { return bkCmd.apply( shellCmdName, conf, args ); } @Override public String description() { // format as org.apache.bookkeeper.bookie.BookieShell.MyCommand.description return StringUtils.isBlank(bkCmd.getUsage()) ? shellCmdName + " [options]" : bkCmd.getUsage(); } @Override public void printUsage() { bkCmd.usage(); } }
47
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/RegistrationClient.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.discover; import java.net.UnknownHostException; import java.util.Set; import java.util.concurrent.CompletableFuture; 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.net.BookieId; import org.apache.bookkeeper.versioning.LongVersion; import org.apache.bookkeeper.versioning.Versioned; /** * A registration client, which the bookkeeper client will use to interact with registration service. */ @LimitedPrivate @Evolving public interface RegistrationClient extends AutoCloseable { /** * Listener to receive changes from the registration service. */ interface RegistrationListener { void onBookiesChanged(Versioned<Set<BookieId>> bookies); } @Override void close(); /** * Get the list of writable bookie identifiers. * * @return a future represents the list of writable bookies. */ CompletableFuture<Versioned<Set<BookieId>>> getWritableBookies(); /** * Get the list of all bookies identifiers. * * @return a future represents the list of all bookies. */ CompletableFuture<Versioned<Set<BookieId>>> getAllBookies(); /** * Get the list of readonly bookie identifiers. * * @return a future represents the list of readonly bookies. */ CompletableFuture<Versioned<Set<BookieId>>> getReadOnlyBookies(); /** * Get detailed information about the services exposed by a Bookie. * For old bookies it is expected to return an empty BookieServiceInfo structure. * * @param bookieId this is the id of the bookie, it can be computed from a {@link BookieId} * @return a future represents the available information. * * @since 4.11 */ default CompletableFuture<Versioned<BookieServiceInfo>> getBookieServiceInfo(BookieId bookieId) { try { BookieServiceInfo bookieServiceInfo = BookieServiceInfoUtils .buildLegacyBookieServiceInfo(bookieId.toString()); return FutureUtils.value(new Versioned<>(bookieServiceInfo, new LongVersion(-1))); } catch (UnknownHostException e) { return FutureUtils.exception(e); } } /** * Watch the changes of bookies. * * <p>The topology changes of bookies will be propagated to the provided <i>listener</i>. * * @param listener listener to receive the topology changes of bookies. * @return a future which completes when the bookies have been read for * the first time */ CompletableFuture<Void> watchWritableBookies(RegistrationListener listener); /** * Unwatch the changes of bookies. * * @param listener listener to receive the topology changes of bookies. */ void unwatchWritableBookies(RegistrationListener listener); /** * Watch the changes of bookies. * * <p>The topology changes of bookies will be propagated to the provided <i>listener</i>. * * @param listener listener to receive the topology changes of bookies. * @return a future which completes when the bookies have been read for * the first time */ CompletableFuture<Void> watchReadOnlyBookies(RegistrationListener listener); /** * Unwatch the changes of bookies. * * @param listener listener to receive the topology changes of bookies. */ void unwatchReadOnlyBookies(RegistrationListener listener); }
48
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/ZKRegistrationClient.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.discover; import static org.apache.bookkeeper.util.BookKeeperConstants.AVAILABLE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.COOKIE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.READONLY; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.stream.Collectors; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BKException.ZKException; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.DataFormats.BookieServiceInfoFormat; import org.apache.bookkeeper.versioning.LongVersion; import org.apache.bookkeeper.versioning.Version; import org.apache.bookkeeper.versioning.Version.Occurred; import org.apache.bookkeeper.versioning.Versioned; import org.apache.zookeeper.KeeperException; 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.Stat; /** * ZooKeeper based {@link RegistrationClient}. */ @Slf4j public class ZKRegistrationClient implements RegistrationClient { static final int ZK_CONNECT_BACKOFF_MS = 200; class WatchTask implements Runnable, Watcher, BiConsumer<Versioned<Set<BookieId>>, Throwable>, AutoCloseable { private final String regPath; private final Set<RegistrationListener> listeners; private volatile boolean closed = false; private Set<BookieId> bookies = null; private Version version = Version.NEW; private final CompletableFuture<Void> firstRunFuture; WatchTask(String regPath, CompletableFuture<Void> firstRunFuture) { this.regPath = regPath; this.listeners = new CopyOnWriteArraySet<>(); this.firstRunFuture = firstRunFuture; } public int getNumListeners() { return listeners.size(); } public boolean addListener(RegistrationListener listener) { if (listeners.add(listener)) { if (null != bookies) { scheduler.execute(() -> { listener.onBookiesChanged( new Versioned<>(bookies, version)); }); } } return true; } public boolean removeListener(RegistrationListener listener) { return listeners.remove(listener); } void watch() { scheduleWatchTask(0L); } private void scheduleWatchTask(long delayMs) { try { scheduler.schedule(this, delayMs, TimeUnit.MILLISECONDS); } catch (RejectedExecutionException ree) { log.warn("Failed to schedule watch bookies task", ree); } } @Override public void run() { if (isClosed()) { return; } getChildren(regPath, this) .whenCompleteAsync(this, scheduler); } @Override public void accept(Versioned<Set<BookieId>> bookieSet, Throwable throwable) { if (throwable != null) { if (firstRunFuture.isDone()) { scheduleWatchTask(ZK_CONNECT_BACKOFF_MS); } else { firstRunFuture.completeExceptionally(throwable); } return; } if (this.version.compare(bookieSet.getVersion()) == Occurred.BEFORE) { this.version = bookieSet.getVersion(); this.bookies = bookieSet.getValue(); if (!listeners.isEmpty()) { for (RegistrationListener listener : listeners) { listener.onBookiesChanged(bookieSet); } } } FutureUtils.complete(firstRunFuture, null); } @Override public void process(WatchedEvent event) { if (EventType.None == event.getType()) { if (KeeperState.Expired == event.getState()) { scheduleWatchTask(ZK_CONNECT_BACKOFF_MS); } return; } // re-read the bookie list scheduleWatchTask(0L); } boolean isClosed() { return closed; } @Override public void close() { closed = true; } } private final ZooKeeper zk; private final ScheduledExecutorService scheduler; @Getter(AccessLevel.PACKAGE) private WatchTask watchWritableBookiesTask = null; @Getter(AccessLevel.PACKAGE) private WatchTask watchReadOnlyBookiesTask = null; private final ConcurrentHashMap<BookieId, Versioned<BookieServiceInfo>> bookieServiceInfoCache = new ConcurrentHashMap<>(); private final Watcher bookieServiceInfoCacheInvalidation; private final boolean bookieAddressTracking; // registration paths private final String bookieRegistrationPath; private final String bookieAllRegistrationPath; private final String bookieReadonlyRegistrationPath; public ZKRegistrationClient(ZooKeeper zk, String ledgersRootPath, ScheduledExecutorService scheduler, boolean bookieAddressTracking) { this.zk = zk; this.scheduler = scheduler; // Following Bookie Network Address Changes is an expensive operation // as it requires additional ZooKeeper watches // we can disable this feature, in case the BK cluster has only // static addresses this.bookieAddressTracking = bookieAddressTracking; this.bookieServiceInfoCacheInvalidation = bookieAddressTracking ? new BookieServiceInfoCacheInvalidationWatcher() : null; this.bookieRegistrationPath = ledgersRootPath + "/" + AVAILABLE_NODE; this.bookieAllRegistrationPath = ledgersRootPath + "/" + COOKIE_NODE; this.bookieReadonlyRegistrationPath = this.bookieRegistrationPath + "/" + READONLY; } @Override public void close() { // no-op } public boolean isBookieAddressTracking() { return bookieAddressTracking; } public ZooKeeper getZk() { return zk; } @Override public CompletableFuture<Versioned<Set<BookieId>>> getWritableBookies() { return getChildren(bookieRegistrationPath, null); } @Override public CompletableFuture<Versioned<Set<BookieId>>> getAllBookies() { return getChildren(bookieAllRegistrationPath, null); } @Override public CompletableFuture<Versioned<Set<BookieId>>> getReadOnlyBookies() { return getChildren(bookieReadonlyRegistrationPath, null); } @Override public CompletableFuture<Versioned<BookieServiceInfo>> getBookieServiceInfo(BookieId bookieId) { // we can only serve data from cache here, // because it can happen than this method is called inside the main // zookeeper client event loop thread Versioned<BookieServiceInfo> resultFromCache = bookieServiceInfoCache.get(bookieId); if (log.isDebugEnabled()) { log.debug("getBookieServiceInfo {} -> {}", bookieId, resultFromCache); } if (resultFromCache != null) { return CompletableFuture.completedFuture(resultFromCache); } else { return FutureUtils.exception(new BKException.BKBookieHandleNotAvailableException()); } } /** * Read BookieServiceInfo from ZooKeeper and updates the local cache. * * @param bookieId * @return an handle to the result of the operation. */ private CompletableFuture<Versioned<BookieServiceInfo>> readBookieServiceInfoAsync(BookieId bookieId) { String pathAsWritable = bookieRegistrationPath + "/" + bookieId; String pathAsReadonly = bookieReadonlyRegistrationPath + "/" + bookieId; CompletableFuture<Versioned<BookieServiceInfo>> promise = new CompletableFuture<>(); zk.getData(pathAsWritable, bookieServiceInfoCacheInvalidation, (int rc, String path, Object o, byte[] bytes, Stat stat) -> { if (KeeperException.Code.OK.intValue() == rc) { try { BookieServiceInfo bookieServiceInfo = deserializeBookieServiceInfo(bookieId, bytes); Versioned<BookieServiceInfo> result = new Versioned<>(bookieServiceInfo, new LongVersion(stat.getCversion())); log.info("Update BookieInfoCache (writable bookie) {} -> {}", bookieId, result.getValue()); bookieServiceInfoCache.put(bookieId, result); promise.complete(result); } catch (IOException ex) { log.error("Cannot update BookieInfo for ", ex); promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path) .initCause(ex)); return; } } else if (KeeperException.Code.NONODE.intValue() == rc) { // not found, looking for a readonly bookie zk.getData(pathAsReadonly, bookieServiceInfoCacheInvalidation, (int rc2, String path2, Object o2, byte[] bytes2, Stat stat2) -> { if (KeeperException.Code.OK.intValue() == rc2) { try { BookieServiceInfo bookieServiceInfo = deserializeBookieServiceInfo(bookieId, bytes2); Versioned<BookieServiceInfo> result = new Versioned<>(bookieServiceInfo, new LongVersion(stat2.getCversion())); log.info("Update BookieInfoCache (readonly bookie) {} -> {}", bookieId, result.getValue()); bookieServiceInfoCache.put(bookieId, result); promise.complete(result); } catch (IOException ex) { log.error("Cannot update BookieInfo for ", ex); promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc2), path2) .initCause(ex)); return; } } else { // not found as writable and readonly, the bookie is offline promise.completeExceptionally(BKException.create(BKException.Code.NoBookieAvailableException)); } }, null); } else { promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc), path)); } }, null); return promise; } @SuppressWarnings("unchecked") @VisibleForTesting static BookieServiceInfo deserializeBookieServiceInfo(BookieId bookieId, byte[] bookieServiceInfo) throws IOException { if (bookieServiceInfo == null || bookieServiceInfo.length == 0) { return BookieServiceInfoUtils.buildLegacyBookieServiceInfo(bookieId.toString()); } BookieServiceInfoFormat builder = BookieServiceInfoFormat.parseFrom(bookieServiceInfo); BookieServiceInfo bsi = new BookieServiceInfo(); List<BookieServiceInfo.Endpoint> endpoints = builder.getEndpointsList().stream() .map(e -> { BookieServiceInfo.Endpoint endpoint = new BookieServiceInfo.Endpoint(); endpoint.setId(e.getId()); endpoint.setPort(e.getPort()); endpoint.setHost(e.getHost()); endpoint.setProtocol(e.getProtocol()); endpoint.setAuth(e.getAuthList()); endpoint.setExtensions(e.getExtensionsList()); return endpoint; }) .collect(Collectors.toList()); bsi.setEndpoints(endpoints); bsi.setProperties(builder.getPropertiesMap()); return bsi; } /** * Reads the list of bookies at the given path and eagerly caches the BookieServiceInfo * structure. * * @param regPath the path on ZooKeeper * @param watcher an optional watcher * @return an handle to the operation */ private CompletableFuture<Versioned<Set<BookieId>>> getChildren(String regPath, Watcher watcher) { CompletableFuture<Versioned<Set<BookieId>>> future = FutureUtils.createFuture(); zk.getChildren(regPath, watcher, (rc, path, ctx, children, stat) -> { if (KeeperException.Code.OK.intValue() != rc) { ZKException zke = new ZKException(KeeperException.create(KeeperException.Code.get(rc), path)); future.completeExceptionally(zke.fillInStackTrace()); return; } Version version = new LongVersion(stat.getCversion()); Set<BookieId> bookies = convertToBookieAddresses(children); List<CompletableFuture<Versioned<BookieServiceInfo>>> bookieInfoUpdated = new ArrayList<>(bookies.size()); for (BookieId id : bookies) { // update the cache for new bookies if (!bookieServiceInfoCache.containsKey(id)) { bookieInfoUpdated.add(readBookieServiceInfoAsync(id)); } } if (bookieInfoUpdated.isEmpty()) { future.complete(new Versioned<>(bookies, version)); } else { FutureUtils .collect(bookieInfoUpdated) .whenComplete((List<Versioned<BookieServiceInfo>> info, Throwable error) -> { // we are ignoring errors intentionally // there could be bookies that publish unparseable information // or other temporary/permanent errors future.complete(new Versioned<>(bookies, version)); }); } }, null); return future; } @Override public synchronized CompletableFuture<Void> watchWritableBookies(RegistrationListener listener) { CompletableFuture<Void> f; if (null == watchWritableBookiesTask) { f = new CompletableFuture<>(); watchWritableBookiesTask = new WatchTask(bookieRegistrationPath, f); f = f.whenComplete((value, cause) -> { if (null != cause) { unwatchWritableBookies(listener); } }); } else { f = watchWritableBookiesTask.firstRunFuture; } watchWritableBookiesTask.addListener(listener); if (watchWritableBookiesTask.getNumListeners() == 1) { watchWritableBookiesTask.watch(); } return f; } @Override public synchronized void unwatchWritableBookies(RegistrationListener listener) { if (null == watchWritableBookiesTask) { return; } watchWritableBookiesTask.removeListener(listener); if (watchWritableBookiesTask.getNumListeners() == 0) { watchWritableBookiesTask.close(); watchWritableBookiesTask = null; } } @Override public synchronized CompletableFuture<Void> watchReadOnlyBookies(RegistrationListener listener) { CompletableFuture<Void> f; if (null == watchReadOnlyBookiesTask) { f = new CompletableFuture<>(); watchReadOnlyBookiesTask = new WatchTask(bookieReadonlyRegistrationPath, f); f = f.whenComplete((value, cause) -> { if (null != cause) { unwatchReadOnlyBookies(listener); } }); } else { f = watchReadOnlyBookiesTask.firstRunFuture; } watchReadOnlyBookiesTask.addListener(listener); if (watchReadOnlyBookiesTask.getNumListeners() == 1) { watchReadOnlyBookiesTask.watch(); } return f; } @Override public synchronized void unwatchReadOnlyBookies(RegistrationListener listener) { if (null == watchReadOnlyBookiesTask) { return; } watchReadOnlyBookiesTask.removeListener(listener); if (watchReadOnlyBookiesTask.getNumListeners() == 0) { watchReadOnlyBookiesTask.close(); watchReadOnlyBookiesTask = null; } } private static HashSet<BookieId> convertToBookieAddresses(List<String> children) { // Read the bookie addresses into a set for efficient lookup HashSet<BookieId> newBookieAddrs = Sets.newHashSet(); for (String bookieAddrString : children) { if (READONLY.equals(bookieAddrString)) { continue; } BookieId bookieAddr = BookieId.parse(bookieAddrString); newBookieAddrs.add(bookieAddr); } return newBookieAddrs; } private static BookieId stripBookieIdFromPath(String path) { if (path == null) { return null; } final int slash = path.lastIndexOf('/'); if (slash >= 0) { try { return BookieId.parse(path.substring(slash + 1)); } catch (IllegalArgumentException e) { log.warn("Cannot decode bookieId from {}", path, e); } } return null; } private class BookieServiceInfoCacheInvalidationWatcher implements Watcher { @Override public void process(WatchedEvent we) { if (log.isDebugEnabled()) { log.debug("zk event {} for {} state {}", we.getType(), we.getPath(), we.getState()); } if (we.getState() == KeeperState.Expired) { log.info("zk session expired, invalidating cache"); bookieServiceInfoCache.clear(); return; } BookieId bookieId = stripBookieIdFromPath(we.getPath()); if (bookieId == null) { return; } switch (we.getType()) { case NodeDeleted: log.info("Invalidate cache for {}", bookieId); bookieServiceInfoCache.remove(bookieId); break; case NodeDataChanged: log.info("refresh cache for {}", bookieId); readBookieServiceInfoAsync(bookieId); break; default: if (log.isDebugEnabled()) { log.debug("ignore cache event {} for {}", we.getType(), bookieId); } break; } } } }
49
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/BookieServiceInfo.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.discover; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Supplier; /** * Information about services exposed by a Bookie. */ public final class BookieServiceInfo { /** * Default empty implementation. */ public static final BookieServiceInfo EMPTY = new BookieServiceInfo( Collections.emptyMap(), Collections.emptyList() ); /** * Default empty implementation. */ public static final Supplier<BookieServiceInfo> NO_INFO = () -> EMPTY; private Map<String, String> properties; private List<Endpoint> endpoints; public BookieServiceInfo(Map<String, String> properties, List<Endpoint> endpoints) { this.properties = Collections.unmodifiableMap(properties); this.endpoints = Collections.unmodifiableList(endpoints); } public BookieServiceInfo() { this(Collections.emptyMap(), Collections.emptyList()); } /** * Unmodifiable map with bookie wide information. * * @return the map */ public Map<String, String> getProperties() { return properties; } /** * Unmodifieable structure with the list of exposed endpoints. * * @return the list. */ public List<Endpoint> getEndpoints() { return endpoints; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public void setEndpoints(List<Endpoint> endpoints) { this.endpoints = endpoints; } /** * Information about an endpoint. */ public static final class Endpoint { private String id; private int port; private String host; private String protocol; private List<String> auth; private List<String> extensions; public Endpoint(String id, int port, String host, String protocol, List<String> auth, List<String> extensions) { this.id = id; this.port = port; this.host = host; this.protocol = protocol; this.auth = auth; this.extensions = extensions; } public Endpoint() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public List<String> getAuth() { return auth; } public void setAuth(List<String> auth) { this.auth = auth; } public List<String> getExtensions() { return extensions; } public void setExtensions(List<String> extensions) { this.extensions = extensions; } @Override public String toString() { return "EndpointInfo{" + "id=" + id + ", port=" + port + ", host=" + host + ", protocol=" + protocol + ", " + "auth=" + auth + ", extensions=" + extensions + '}'; } } @Override public String toString() { return "BookieServiceInfo{" + "properties=" + properties + ", endpoints=" + endpoints + '}'; } }
50
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/BookieServiceInfoUtils.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.discover; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collections; import org.apache.bookkeeper.net.BookieSocketAddress; /** * Utility class for {@link BookieServiceInfo}. */ public final class BookieServiceInfoUtils { /** * Creates a default legacy bookie info implementation. * In the default implementation there is one endpoint with * <code>bookie-rpc</code> protocol and the bookie id in the host port. * * @param bookieId bookie id * @return default implementation of a BookieServiceInfo * @throws UnknownHostException if the given bookieId is invalid */ public static BookieServiceInfo buildLegacyBookieServiceInfo(String bookieId) throws UnknownHostException { BookieSocketAddress address = new BookieSocketAddress(bookieId); BookieServiceInfo.Endpoint endpoint = new BookieServiceInfo.Endpoint(); endpoint.setId(bookieId); endpoint.setHost(address.getHostName()); endpoint.setPort(address.getPort()); endpoint.setProtocol("bookie-rpc"); endpoint.setAuth(Collections.emptyList()); endpoint.setExtensions(Collections.emptyList()); return new BookieServiceInfo(Collections.emptyMap(), Arrays.asList(endpoint)); } }
51
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/ZKRegistrationManager.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.discover; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.bookkeeper.util.BookKeeperConstants.AVAILABLE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.COOKIE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.EMPTY_BYTE_ARRAY; import static org.apache.bookkeeper.util.BookKeeperConstants.INSTANCEID; import static org.apache.bookkeeper.util.BookKeeperConstants.READONLY; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.BookieIllegalOpException; import org.apache.bookkeeper.bookie.BookieException.CookieExistException; import org.apache.bookkeeper.bookie.BookieException.CookieNotFoundException; import org.apache.bookkeeper.bookie.BookieException.MetadataStoreException; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BKException.BKInterruptedException; import org.apache.bookkeeper.client.BKException.MetaStoreException; import org.apache.bookkeeper.common.concurrent.FutureUtils; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.meta.AbstractZkLedgerManagerFactory; import org.apache.bookkeeper.meta.LayoutManager; import org.apache.bookkeeper.meta.LedgerManagerFactory; import org.apache.bookkeeper.meta.ZkLayoutManager; import org.apache.bookkeeper.meta.ZkLedgerUnderreplicationManager; import org.apache.bookkeeper.meta.zk.ZKMetadataDriverBase; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.DataFormats.BookieServiceInfoFormat; import org.apache.bookkeeper.util.BookKeeperConstants; import org.apache.bookkeeper.util.ZkUtils; import org.apache.bookkeeper.versioning.LongVersion; import org.apache.bookkeeper.versioning.Version; import org.apache.bookkeeper.versioning.Versioned; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.KeeperException.NoNodeException; import org.apache.zookeeper.KeeperException.NodeExistsException; import org.apache.zookeeper.Op; 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.ZKUtil; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Stat; /** * ZooKeeper Based {@link RegistrationManager}. */ @Slf4j public class ZKRegistrationManager implements RegistrationManager { private static final Function<Throwable, BKException> EXCEPTION_FUNC = cause -> { if (cause instanceof BKException) { log.error("Failed to get bookie list : ", cause); return (BKException) cause; } else if (cause instanceof InterruptedException) { log.error("Interrupted reading bookie list : ", cause); return new BKInterruptedException(); } else { return new MetaStoreException(); } }; private final ServerConfiguration conf; private final ZooKeeper zk; private final List<ACL> zkAcls; private final LayoutManager layoutManager; private volatile boolean zkRegManagerInitialized = false; // ledgers root path private final String ledgersRootPath; // cookie path private final String cookiePath; // registration paths protected final String bookieRegistrationPath; protected final String bookieReadonlyRegistrationPath; // session timeout in milliseconds private final int zkTimeoutMs; private final List<RegistrationListener> listeners = new ArrayList<>(); public ZKRegistrationManager(ServerConfiguration conf, ZooKeeper zk) { this(conf, zk, ZKMetadataDriverBase.resolveZkLedgersRootPath(conf)); } public ZKRegistrationManager(ServerConfiguration conf, ZooKeeper zk, String ledgersRootPath) { this.conf = conf; this.zk = zk; this.zkAcls = ZkUtils.getACLs(conf); this.ledgersRootPath = ledgersRootPath; this.cookiePath = ledgersRootPath + "/" + COOKIE_NODE; this.bookieRegistrationPath = ledgersRootPath + "/" + AVAILABLE_NODE; this.bookieReadonlyRegistrationPath = this.bookieRegistrationPath + "/" + READONLY; this.zkTimeoutMs = conf.getZkTimeout(); this.layoutManager = new ZkLayoutManager( zk, ledgersRootPath, zkAcls); this.zk.register(event -> { if (!zkRegManagerInitialized) { // do nothing until first registration return; } // Check for expired connection. if (event.getType().equals(EventType.None) && event.getState().equals(KeeperState.Expired)) { listeners.forEach(RegistrationListener::onRegistrationExpired); } }); } @Override public void close() { // no-op } /** * Returns the CookiePath of the bookie in the ZooKeeper. * * @param bookieId bookie id * @return */ public String getCookiePath(BookieId bookieId) { return this.cookiePath + "/" + bookieId; } // // Registration Management // /** * Check existence of <i>regPath</i> and wait it expired if possible. * * @param regPath reg node path. * @return true if regPath exists, otherwise return false * @throws IOException if can't create reg path */ protected boolean checkRegNodeAndWaitExpired(String regPath) throws IOException { final CountDownLatch prevNodeLatch = new CountDownLatch(1); Watcher zkPrevRegNodewatcher = new Watcher() { @Override public void process(WatchedEvent event) { // Check for prev znode deletion. Connection expiration is // not handling, since bookie has logic to shutdown. if (EventType.NodeDeleted == event.getType()) { prevNodeLatch.countDown(); } } }; try { Stat stat = zk.exists(regPath, zkPrevRegNodewatcher); if (null != stat) { // if the ephemeral owner isn't current zookeeper client // wait for it to be expired. if (stat.getEphemeralOwner() != zk.getSessionId()) { log.info("Previous bookie registration znode: {} exists, so waiting zk sessiontimeout:" + " {} ms for znode deletion", regPath, zkTimeoutMs); // waiting for the previous bookie reg znode deletion if (!prevNodeLatch.await(zkTimeoutMs, TimeUnit.MILLISECONDS)) { throw new NodeExistsException(regPath); } else { return false; } } return true; } else { return false; } } catch (KeeperException ke) { log.error("ZK exception checking and wait ephemeral znode {} expired : ", regPath, ke); throw new IOException("ZK exception checking and wait ephemeral znode " + regPath + " expired", ke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("Interrupted checking and wait ephemeral znode {} expired : ", regPath, ie); throw new IOException("Interrupted checking and wait ephemeral znode " + regPath + " expired", ie); } } @Override public void registerBookie(BookieId bookieId, boolean readOnly, BookieServiceInfo bookieServiceInfo) throws BookieException { if (!readOnly) { String regPath = bookieRegistrationPath + "/" + bookieId; doRegisterBookie(regPath, bookieServiceInfo); } else { doRegisterReadOnlyBookie(bookieId, bookieServiceInfo); } } @VisibleForTesting static byte[] serializeBookieServiceInfo(BookieServiceInfo bookieServiceInfo) { if (log.isDebugEnabled()) { log.debug("serialize BookieServiceInfo {}", bookieServiceInfo); } try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { BookieServiceInfoFormat.Builder builder = BookieServiceInfoFormat.newBuilder(); List<BookieServiceInfoFormat.Endpoint> bsiEndpoints = bookieServiceInfo.getEndpoints().stream() .map(e -> { return BookieServiceInfoFormat.Endpoint.newBuilder() .setId(e.getId()) .setPort(e.getPort()) .setHost(e.getHost()) .setProtocol(e.getProtocol()) .addAllAuth(e.getAuth()) .addAllExtensions(e.getExtensions()) .build(); }) .collect(Collectors.toList()); builder.addAllEndpoints(bsiEndpoints); builder.putAllProperties(bookieServiceInfo.getProperties()); builder.build().writeTo(os); return os.toByteArray(); } catch (IOException err) { log.error("Cannot serialize bookieServiceInfo from " + bookieServiceInfo); throw new RuntimeException(err); } } private void doRegisterBookie(String regPath, BookieServiceInfo bookieServiceInfo) throws BookieException { // ZK ephemeral node for this Bookie. try { if (!checkRegNodeAndWaitExpired(regPath)) { // Create the ZK ephemeral node for this Bookie. zk.create(regPath, serializeBookieServiceInfo(bookieServiceInfo), zkAcls, CreateMode.EPHEMERAL); zkRegManagerInitialized = true; } } catch (KeeperException ke) { log.error("ZK exception registering ephemeral Znode for Bookie!", ke); // Throw an IOException back up. This will cause the Bookie // constructor to error out. Alternatively, we could do a System // exit here as this is a fatal error. throw new MetadataStoreException(ke); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("Interrupted exception registering ephemeral Znode for Bookie!", ie); // Throw an IOException back up. This will cause the Bookie // constructor to error out. Alternatively, we could do a System // exit here as this is a fatal error. throw new MetadataStoreException(ie); } catch (IOException e) { throw new MetadataStoreException(e); } } private void doRegisterReadOnlyBookie(BookieId bookieId, BookieServiceInfo bookieServiceInfo) throws BookieException { try { if (null == zk.exists(this.bookieReadonlyRegistrationPath, false)) { try { zk.create(this.bookieReadonlyRegistrationPath, serializeBookieServiceInfo(bookieServiceInfo), zkAcls, CreateMode.PERSISTENT); } catch (NodeExistsException e) { // this node is just now created by someone. } } String regPath = bookieReadonlyRegistrationPath + "/" + bookieId; doRegisterBookie(regPath, bookieServiceInfo); // clear the write state regPath = bookieRegistrationPath + "/" + bookieId; try { // Clear the current registered node zk.delete(regPath, -1); } catch (KeeperException.NoNodeException nne) { log.warn("No writable bookie registered node {} when transitioning to readonly", regPath, nne); } } catch (KeeperException | InterruptedException e) { throw new MetadataStoreException(e); } } @Override public void unregisterBookie(BookieId bookieId, boolean readOnly) throws BookieException { String regPath; if (!readOnly) { regPath = bookieRegistrationPath + "/" + bookieId; } else { regPath = bookieReadonlyRegistrationPath + "/" + bookieId; } doUnregisterBookie(regPath); } private void doUnregisterBookie(String regPath) throws BookieException { try { zk.delete(regPath, -1); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new MetadataStoreException(ie); } catch (KeeperException e) { throw new MetadataStoreException(e); } } // // Cookie Management // @Override public void writeCookie(BookieId bookieId, Versioned<byte[]> cookieData) throws BookieException { String zkPath = getCookiePath(bookieId); try { if (Version.NEW == cookieData.getVersion()) { if (zk.exists(cookiePath, false) == null) { try { zk.create(cookiePath, new byte[0], zkAcls, CreateMode.PERSISTENT); } catch (NodeExistsException nne) { log.info("More than one bookie tried to create {} at once. Safe to ignore.", cookiePath); } } zk.create(zkPath, cookieData.getValue(), zkAcls, CreateMode.PERSISTENT); } else { if (!(cookieData.getVersion() instanceof LongVersion)) { throw new BookieIllegalOpException("Invalid version type, expected it to be LongVersion"); } zk.setData( zkPath, cookieData.getValue(), (int) ((LongVersion) cookieData.getVersion()).getLongVersion()); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); throw new MetadataStoreException("Interrupted writing cookie for bookie " + bookieId, ie); } catch (NoNodeException nne) { throw new CookieNotFoundException(bookieId.toString()); } catch (NodeExistsException nee) { throw new CookieExistException(bookieId.toString()); } catch (KeeperException e) { throw new MetadataStoreException("Failed to write cookie for bookie " + bookieId); } } @Override public Versioned<byte[]> readCookie(BookieId bookieId) throws BookieException { String zkPath = getCookiePath(bookieId); try { Stat stat = zk.exists(zkPath, false); byte[] data = zk.getData(zkPath, false, stat); // sets stat version from ZooKeeper LongVersion version = new LongVersion(stat.getVersion()); return new Versioned<>(data, version); } catch (NoNodeException nne) { throw new CookieNotFoundException(bookieId.toString()); } catch (KeeperException | InterruptedException e) { throw new MetadataStoreException("Failed to read cookie for bookie " + bookieId); } } @Override public void removeCookie(BookieId bookieId, Version version) throws BookieException { String zkPath = getCookiePath(bookieId); try { zk.delete(zkPath, (int) ((LongVersion) version).getLongVersion()); } catch (NoNodeException e) { throw new CookieNotFoundException(bookieId.toString()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new MetadataStoreException("Interrupted deleting cookie for bookie " + bookieId, e); } catch (KeeperException e) { throw new MetadataStoreException("Failed to delete cookie for bookie " + bookieId); } log.info("Removed cookie from {} for bookie {}.", cookiePath, bookieId); } @Override public String getClusterInstanceId() throws BookieException { String instanceId = null; try { if (zk.exists(ledgersRootPath, null) == null) { log.error("BookKeeper metadata doesn't exist in zookeeper. " + "Has the cluster been initialized? " + "Try running bin/bookkeeper shell metaformat"); throw new KeeperException.NoNodeException("BookKeeper metadata"); } try { byte[] data = zk.getData(ledgersRootPath + "/" + INSTANCEID, false, null); instanceId = new String(data, UTF_8); } catch (KeeperException.NoNodeException e) { log.info("INSTANCEID not exists in zookeeper. Not considering it for data verification"); } } catch (KeeperException | InterruptedException e) { throw new MetadataStoreException("Failed to get cluster instance id", e); } return instanceId; } @Override public boolean prepareFormat() throws Exception { boolean ledgerRootExists = null != zk.exists(ledgersRootPath, false); boolean availableNodeExists = null != zk.exists(bookieRegistrationPath, false); // Create ledgers root node if not exists if (!ledgerRootExists) { ZkUtils.createFullPathOptimistic(zk, ledgersRootPath, "".getBytes(StandardCharsets.UTF_8), zkAcls, CreateMode.PERSISTENT); } // create available bookies node if not exists if (!availableNodeExists) { zk.create(bookieRegistrationPath, "".getBytes(StandardCharsets.UTF_8), zkAcls, CreateMode.PERSISTENT); } // create readonly bookies node if not exists if (null == zk.exists(bookieReadonlyRegistrationPath, false)) { zk.create(bookieReadonlyRegistrationPath, new byte[0], zkAcls, CreateMode.PERSISTENT); } return ledgerRootExists; } @Override public boolean initNewCluster() throws Exception { String zkServers = ZKMetadataDriverBase.resolveZkServers(conf); String instanceIdPath = ledgersRootPath + "/" + INSTANCEID; log.info("Initializing ZooKeeper metadata for new cluster, ZKServers: {} ledger root path: {}", zkServers, ledgersRootPath); boolean ledgerRootExists = null != zk.exists(ledgersRootPath, false); if (ledgerRootExists) { log.error("Ledger root path: {} already exists", ledgersRootPath); return false; } List<Op> multiOps = Lists.newArrayListWithExpectedSize(4); // Create ledgers root node multiOps.add(Op.create(ledgersRootPath, EMPTY_BYTE_ARRAY, zkAcls, CreateMode.PERSISTENT)); // create available bookies node multiOps.add(Op.create(bookieRegistrationPath, EMPTY_BYTE_ARRAY, zkAcls, CreateMode.PERSISTENT)); // create readonly bookies node multiOps.add(Op.create( bookieReadonlyRegistrationPath, EMPTY_BYTE_ARRAY, zkAcls, CreateMode.PERSISTENT)); // create INSTANCEID String instanceId = UUID.randomUUID().toString(); multiOps.add(Op.create(instanceIdPath, instanceId.getBytes(UTF_8), zkAcls, CreateMode.PERSISTENT)); // execute the multi ops zk.multi(multiOps); // creates the new layout and stores in zookeeper AbstractZkLedgerManagerFactory.newLedgerManagerFactory(conf, layoutManager); log.info("Successfully initiated cluster. ZKServers: {} ledger root path: {} instanceId: {}", zkServers, ledgersRootPath, instanceId); return true; } @Override public boolean nukeExistingCluster() throws Exception { String zkServers = ZKMetadataDriverBase.resolveZkServers(conf); log.info("Nuking ZooKeeper metadata of existing cluster, ZKServers: {} ledger root path: {}", zkServers, ledgersRootPath); boolean ledgerRootExists = null != zk.exists(ledgersRootPath, false); if (!ledgerRootExists) { log.info("There is no existing cluster with ledgersRootPath: {} in ZKServers: {}, " + "so exiting nuke operation", ledgersRootPath, zkServers); return true; } boolean availableNodeExists = null != zk.exists(bookieRegistrationPath, false); try (RegistrationClient regClient = new ZKRegistrationClient( zk, ledgersRootPath, null, false )) { if (availableNodeExists) { Collection<BookieId> rwBookies = FutureUtils .result(regClient.getWritableBookies(), EXCEPTION_FUNC).getValue(); if (rwBookies != null && !rwBookies.isEmpty()) { log.error("Bookies are still up and connected to this cluster, " + "stop all bookies before nuking the cluster"); return false; } boolean readonlyNodeExists = null != zk.exists(bookieReadonlyRegistrationPath, false); if (readonlyNodeExists) { Collection<BookieId> roBookies = FutureUtils .result(regClient.getReadOnlyBookies(), EXCEPTION_FUNC).getValue(); if (roBookies != null && !roBookies.isEmpty()) { log.error("Readonly Bookies are still up and connected to this cluster, " + "stop all bookies before nuking the cluster"); return false; } } } } LedgerManagerFactory ledgerManagerFactory = AbstractZkLedgerManagerFactory.newLedgerManagerFactory(conf, layoutManager); return ledgerManagerFactory.validateAndNukeExistingCluster(conf, layoutManager); } @Override public boolean format() throws Exception { // Clear underreplicated ledgers try { ZKUtil.deleteRecursive(zk, ZkLedgerUnderreplicationManager.getBasePath(ledgersRootPath) + BookKeeperConstants.DEFAULT_ZK_LEDGERS_ROOT_PATH); } catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { log.debug("underreplicated ledgers root path node not exists in zookeeper to delete"); } } // Clear underreplicatedledger locks try { ZKUtil.deleteRecursive(zk, ZkLedgerUnderreplicationManager.getBasePath(ledgersRootPath) + '/' + BookKeeperConstants.UNDER_REPLICATION_LOCK); } catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { log.debug("underreplicatedledger locks node not exists in zookeeper to delete"); } } // Clear the cookies try { ZKUtil.deleteRecursive(zk, cookiePath); } catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { log.debug("cookies node not exists in zookeeper to delete"); } } // Clear the INSTANCEID try { zk.delete(ledgersRootPath + "/" + BookKeeperConstants.INSTANCEID, -1); } catch (KeeperException.NoNodeException e) { if (log.isDebugEnabled()) { log.debug("INSTANCEID not exists in zookeeper to delete"); } } // create INSTANCEID String instanceId = UUID.randomUUID().toString(); zk.create(ledgersRootPath + "/" + BookKeeperConstants.INSTANCEID, instanceId.getBytes(StandardCharsets.UTF_8), zkAcls, CreateMode.PERSISTENT); log.info("Successfully formatted BookKeeper metadata"); return true; } @Override public boolean isBookieRegistered(BookieId bookieId) throws BookieException { String regPath = bookieRegistrationPath + "/" + bookieId; String readonlyRegPath = bookieReadonlyRegistrationPath + "/" + bookieId; try { return ((null != zk.exists(regPath, false)) || (null != zk.exists(readonlyRegPath, false))); } catch (KeeperException e) { log.error("ZK exception while checking registration ephemeral znodes for BookieId: {}", bookieId, e); throw new MetadataStoreException(e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); log.error("InterruptedException while checking registration ephemeral znodes for BookieId: {}", bookieId, e); throw new MetadataStoreException(e); } } @Override public void addRegistrationListener(RegistrationListener listener) { listeners.add(listener); } }
52
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/RegistrationManager.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.discover; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.common.annotation.InterfaceAudience.LimitedPrivate; import org.apache.bookkeeper.common.annotation.InterfaceStability.Evolving; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.versioning.Version; import org.apache.bookkeeper.versioning.Versioned; /** * Registration manager interface, which a bookie server will use to do the registration process. */ @LimitedPrivate @Evolving public interface RegistrationManager extends AutoCloseable { /** * Registration Listener on listening the registration state. */ @FunctionalInterface interface RegistrationListener { /** * Signal when registration is expired. */ void onRegistrationExpired(); } @Override void close(); /** * Return the cluster instance id. * * @return the cluster instance id. */ String getClusterInstanceId() throws BookieException; /** * Registering the bookie server as <i>bookieId</i>. * * @param bookieId bookie id * @param readOnly whether to register it as writable or readonly * @param serviceInfo information about services exposed by the Bookie * @throws BookieException when fail to register a bookie. */ void registerBookie(BookieId bookieId, boolean readOnly, BookieServiceInfo serviceInfo) throws BookieException; /** * Unregistering the bookie server as <i>bookieId</i>. * * @param bookieId bookie id * @param readOnly whether to register it as writable or readonly * @throws BookieException when fail to unregister a bookie. */ void unregisterBookie(BookieId bookieId, boolean readOnly) throws BookieException; /** * Checks if Bookie with the given BookieId is registered as readwrite or * readonly bookie. * * @param bookieId bookie id * @return returns true if a bookie with bookieid is currently registered as * readwrite or readonly bookie. * @throws BookieException */ boolean isBookieRegistered(BookieId bookieId) throws BookieException; /** * Write the cookie data, which will be used for verifying the integrity of the bookie environment. * * @param bookieId bookie id * @param cookieData cookie data * @throws BookieException when fail to write cookie */ void writeCookie(BookieId bookieId, Versioned<byte[]> cookieData) throws BookieException; /** * Read the cookie data, which will be used for verifying the integrity of the bookie environment. * * @param bookieId bookie id * @return versioned cookie data * @throws BookieException when fail to read cookie */ Versioned<byte[]> readCookie(BookieId bookieId) throws BookieException; /** * Remove the cookie data. * * @param bookieId bookie id * @param version version of the cookie data * @throws BookieException when fail to remove cookie */ void removeCookie(BookieId bookieId, Version version) throws BookieException; /** * Prepare ledgers root node, availableNode, readonly node.. * * @return Returns true if old data exists, false if not. */ boolean prepareFormat() throws Exception; /** * Initializes new cluster by creating required znodes for the cluster. If * ledgersrootpath is already existing then it will error out. * * @return returns true if new cluster is successfully created or false if it failed to initialize. * @throws Exception */ boolean initNewCluster() throws Exception; /** * Do format boolean. * * @return Returns true if success do format, false if not. */ boolean format() throws Exception; /** * Nukes existing cluster metadata. * * @return returns true if cluster metadata is successfully nuked * or false if it failed to nuke the cluster metadata. * @throws Exception */ boolean nukeExistingCluster() throws Exception; /** * Add a listener to be triggered when an registration event occurs. * * @param listener the listener to be added */ void addRegistrationListener(RegistrationListener listener); }
53
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/discover/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 related to service discovery. */ package org.apache.bookkeeper.discover;
54
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/StabilizeNetworkTopology.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.net; import io.netty.util.HashedWheelTimer; import io.netty.util.Timeout; import io.netty.util.TimerTask; import java.util.Collection; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This is going to provide a stabilize network topology regarding to flapping zookeeper registration. */ public class StabilizeNetworkTopology implements NetworkTopology { private static final Logger logger = LoggerFactory.getLogger(StabilizeNetworkTopology.class); static class NodeStatus { long lastPresentTime; boolean tentativeToRemove; NodeStatus() { this.lastPresentTime = System.currentTimeMillis(); } synchronized boolean isTentativeToRemove() { return tentativeToRemove; } synchronized NodeStatus updateStatus(boolean tentativeToRemove) { this.tentativeToRemove = tentativeToRemove; if (!this.tentativeToRemove) { this.lastPresentTime = System.currentTimeMillis(); } return this; } synchronized long getLastPresentTime() { return this.lastPresentTime; } } protected final NetworkTopologyImpl impl; // timer protected final HashedWheelTimer timer; // statuses protected final ConcurrentMap<Node, NodeStatus> nodeStatuses; // stabilize period seconds protected final long stabilizePeriodMillis; private class RemoveNodeTask implements TimerTask { private final Node node; RemoveNodeTask(Node node) { this.node = node; } @Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } NodeStatus status = nodeStatuses.get(node); if (null == status) { // no status of this node, remove this node from topology impl.remove(node); } else if (status.isTentativeToRemove()) { long millisSinceLastSeen = System.currentTimeMillis() - status.getLastPresentTime(); if (millisSinceLastSeen >= stabilizePeriodMillis) { logger.info("Node {} (seen @ {}) becomes stale for {} ms, remove it from the topology.", node, status.getLastPresentTime(), millisSinceLastSeen); impl.remove(node); nodeStatuses.remove(node, status); } } } } public StabilizeNetworkTopology(HashedWheelTimer timer, int stabilizePeriodSeconds) { this.impl = new NetworkTopologyImpl(); this.timer = timer; this.nodeStatuses = new ConcurrentHashMap<Node, NodeStatus>(); this.stabilizePeriodMillis = TimeUnit.SECONDS.toMillis(stabilizePeriodSeconds); } void updateNode(Node node, boolean tentativeToRemove) { NodeStatus ns = nodeStatuses.get(node); if (null == ns) { NodeStatus newStatus = new NodeStatus(); NodeStatus oldStatus = nodeStatuses.putIfAbsent(node, newStatus); if (null == oldStatus) { ns = newStatus; } else { ns = oldStatus; } } ns.updateStatus(tentativeToRemove); } @Override public void add(Node node) { updateNode(node, false); this.impl.add(node); } @Override public void remove(Node node) { updateNode(node, true); timer.newTimeout(new RemoveNodeTask(node), stabilizePeriodMillis, TimeUnit.MILLISECONDS); } @Override public boolean contains(Node node) { return impl.contains(node); } @Override public Node getNode(String loc) { return impl.getNode(loc); } @Override public int getNumOfRacks() { return impl.getNumOfRacks(); } @Override public Set<Node> getLeaves(String loc) { return impl.getLeaves(loc); } @Override public int countNumOfAvailableNodes(String scope, Collection<Node> excludedNodes) { return impl.countNumOfAvailableNodes(scope, excludedNodes); } }
55
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/CachedDNSToSwitchMapping.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.net; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * A cached implementation of DNSToSwitchMapping that takes an * raw DNSToSwitchMapping and stores the resolved network location in * a cache. The following calls to a resolved network location * will get its location from the cache. * */ public class CachedDNSToSwitchMapping extends AbstractDNSToSwitchMapping { private Map<String, String> cache = new ConcurrentHashMap<String, String>(); /** * The uncached mapping. */ protected final DNSToSwitchMapping rawMapping; /** * Cache a raw DNS mapping. * @param rawMapping the raw mapping to cache */ public CachedDNSToSwitchMapping(DNSToSwitchMapping rawMapping) { this.rawMapping = rawMapping; } // we'll use IP Address for these mappings. @Override public boolean useHostName() { return false; } /** * @param names a list of hostnames to probe for being cached * @return the hosts from 'names' that have not been cached previously */ private List<String> getUncachedHosts(List<String> names) { // find out all names without cached resolved location List<String> unCachedHosts = new ArrayList<String>(names.size()); for (String name : names) { if (cache.get(name) == null) { unCachedHosts.add(name); } } return unCachedHosts; } /** * Caches the resolved host:rack mappings. The two list * parameters must be of equal size. * * @param uncachedHosts a list of hosts that were uncached * @param resolvedHosts a list of resolved host entries where the element * at index(i) is the resolved value for the entry in uncachedHosts[i] */ private void cacheResolvedHosts(List<String> uncachedHosts, List<String> resolvedHosts) { // Cache the result if (resolvedHosts != null) { for (int i = 0; i < uncachedHosts.size(); i++) { cache.put(uncachedHosts.get(i), resolvedHosts.get(i)); } } } /** * @param names a list of hostnames to look up (can be be empty) * @return the cached resolution of the list of hostnames/addresses. * or null if any of the names are not currently in the cache */ private List<String> getCachedHosts(List<String> names) { List<String> result = new ArrayList<String>(names.size()); // Construct the result for (String name : names) { String networkLocation = cache.get(name); if (networkLocation != null) { result.add(networkLocation); } else { return null; } } return result; } @Override public List<String> resolve(List<String> names) { // normalize all input names to be in the form of IP addresses names = NetUtils.normalizeHostNames(names); List <String> result = new ArrayList<String>(names.size()); if (names.isEmpty()) { return result; } List<String> uncachedHosts = getUncachedHosts(names); // Resolve the uncached hosts List<String> resolvedHosts = rawMapping.resolve(uncachedHosts); //cache them cacheResolvedHosts(uncachedHosts, resolvedHosts); //now look up the entire list in the cache return getCachedHosts(names); } /** * Get the (host x switch) map. * @return a copy of the cached map of hosts to rack */ @Override public Map<String, String> getSwitchMap() { Map<String, String> switchMap = new HashMap<String, String>(cache); return switchMap; } @Override public String toString() { return "cached switch mapping relaying to " + rawMapping; } /** * Delegate the switch topology query to the raw mapping, via * {@link AbstractDNSToSwitchMapping#isMappingSingleSwitch(DNSToSwitchMapping)}. * @return true iff the raw mapper is considered single-switch. */ @Override public boolean isSingleSwitch() { return isMappingSingleSwitch(rawMapping); } @Override public void reloadCachedMappings() { cache.clear(); } }
56
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/ScriptBasedMapping.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.net; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import org.apache.bookkeeper.util.Shell.ShellCommandExecutor; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class implements the {@link DNSToSwitchMapping} interface using a * script configured via the * {@link CommonConfigurationKeys#NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY} option. * <p/> * It contains a static class <code>RawScriptBasedMapping</code> that performs * the work: reading the configuration parameters, executing any defined * script, handling errors and such like. The outer * class extends {@link CachedDNSToSwitchMapping} to cache the delegated * queries. * <p/> * This DNS mapper's {@link #isSingleSwitch()} predicate returns * true if and only if a script is defined. */ public final class ScriptBasedMapping extends CachedDNSToSwitchMapping { /** * Minimum number of arguments: {@value}. */ static final int MIN_ALLOWABLE_ARGS = 1; /** * Default number of arguments: {@value}. */ static final int DEFAULT_ARG_COUNT = CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_DEFAULT; /** * Key to the script filename {@value}. */ static final String SCRIPT_FILENAME_KEY = CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY; /** * Key to the argument count that the script supports * {@value}. */ static final String SCRIPT_ARG_COUNT_KEY = CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_KEY; /** * Text used in the {@link #toString()} method if there is no string * {@value}. */ public static final String NO_SCRIPT = "no script"; /** * Create an instance with the default configuration. * * <p>Calling {@link #setConf(Configuration)} will trigger a * re-evaluation of the configuration settings and so be used to * set up the mapping script. * */ public ScriptBasedMapping() { super(new RawScriptBasedMapping()); } /** * Create an instance from the given configuration. * @param conf configuration */ public ScriptBasedMapping(Configuration conf) { this(); setConf(conf); } /** * Get the cached mapping and convert it to its real type. * @return the inner raw script mapping. */ private RawScriptBasedMapping getRawMapping() { return (RawScriptBasedMapping) rawMapping; } @Override public Configuration getConf() { return getRawMapping().getConf(); } @Override public String toString() { return "script-based mapping with " + getRawMapping().toString(); } /** * {@inheritDoc} * * <p>This will get called in the superclass constructor, so a check is needed * to ensure that the raw mapping is defined before trying to relaying a null * configuration. * @param conf */ @Override public void setConf(Configuration conf) { super.setConf(conf); getRawMapping().setConf(conf); } /** * This is the uncached script mapping that is fed into the cache managed * by the superclass {@link CachedDNSToSwitchMapping}. */ private static final class RawScriptBasedMapping extends AbstractDNSToSwitchMapping { private String scriptName; private int maxArgs; //max hostnames per call of the script private static final Logger LOG = LoggerFactory.getLogger(RawScriptBasedMapping.class); /* * extract 'scriptName' and 'maxArgs' parameters from the conf and throw * RuntimeException if 'scriptName' is null. Also for sanity check * purpose try executing the script with no arguments. Here it is * expected that running script with no arguments would do sanity check * of the script and the env, and return successfully if script and env. * are valid. If sanity check of the script with no argument fails then * throw RuntimeException. * */ @Override protected void validateConf() { Configuration conf = getConf(); if (conf != null) { String scriptNameConfValue = conf.getString(SCRIPT_FILENAME_KEY); if (StringUtils.isNotBlank(scriptNameConfValue)) { scriptName = scriptNameConfValue; maxArgs = conf.getInt(SCRIPT_ARG_COUNT_KEY, DEFAULT_ARG_COUNT); } else { scriptName = null; maxArgs = 0; } } else { scriptName = null; maxArgs = 0; } if (null == scriptName) { throw new RuntimeException("No network topology script is found when using script" + " based DNS resolver."); } else { File dir = null; String userDir; if ((userDir = System.getProperty("user.dir")) != null) { dir = new File(userDir); } String[] execString = { this.scriptName }; ShellCommandExecutor s = new ShellCommandExecutor(execString, dir); try { s.execute(); } catch (Exception e) { LOG.error("Conf validation failed. Got exception for sanity check of script: " + this.scriptName, e); throw new RuntimeException( "Conf validation failed. Got exception for sanity check of script: " + this.scriptName, e); } } } /** * Constructor. The mapping is not ready to use until * {@link #setConf(Configuration)} has been called */ public RawScriptBasedMapping() { } @Override public List<String> resolve(List<String> names) { List<String> m = new ArrayList<String>(names.size()); if (names.isEmpty()) { return m; } if (scriptName == null) { return null; } String output = runResolveCommand(names); if (output != null) { StringTokenizer allSwitchInfo = new StringTokenizer(output); while (allSwitchInfo.hasMoreTokens()) { String switchInfo = allSwitchInfo.nextToken(); m.add(switchInfo); } if (m.size() != names.size()) { // invalid number of entries returned by the script LOG.error("Script " + scriptName + " returned " + m.size() + " values when " + names.size() + " were expected."); return null; } } else { // an error occurred. return null to signify this. // (exn was already logged in runResolveCommand) return null; } return m; } /** * Build and execute the resolution command. The command is * executed in the directory specified by the system property * "user.dir" if set; otherwise the current working directory is used * @param args a list of arguments * @return null if the number of arguments is out of range, * or the output of the command. */ private String runResolveCommand(List<String> args) { int loopCount = 0; if (args.size() == 0) { return null; } StringBuilder allOutput = new StringBuilder(); int numProcessed = 0; if (maxArgs < MIN_ALLOWABLE_ARGS) { LOG.warn("Invalid value " + maxArgs + " for " + SCRIPT_ARG_COUNT_KEY + "; must be >= " + MIN_ALLOWABLE_ARGS); return null; } while (numProcessed != args.size()) { int start = maxArgs * loopCount; List<String> cmdList = new ArrayList<String>(); cmdList.add(scriptName); for (numProcessed = start; numProcessed < (start + maxArgs) && numProcessed < args.size(); numProcessed++) { cmdList.add(args.get(numProcessed)); } File dir = null; String userDir; if ((userDir = System.getProperty("user.dir")) != null) { dir = new File(userDir); } ShellCommandExecutor s = new ShellCommandExecutor(cmdList.toArray(new String[cmdList.size()]), dir); try { s.execute(); allOutput.append(s.getOutput()).append(" "); } catch (Exception e) { LOG.warn("Exception running: {} Exception message: {}", s, e.getMessage()); return null; } loopCount++; } return allOutput.toString(); } /** * Declare that the mapper is single-switched if a script was not named * in the configuration. * @return true iff there is no script */ @Override public boolean isSingleSwitch() { return scriptName == null; } @Override public String toString() { return scriptName != null ? ("script " + scriptName) : NO_SCRIPT; } @Override public void reloadCachedMappings() { // Nothing to do here, since RawScriptBasedMapping has no cache, and // does not inherit from CachedDNSToSwitchMapping } } }
57
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/Node.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.net; import com.google.common.annotations.Beta; /** The interface defines a node in a network topology. * A node may be a leave representing a data node or an inner * node representing a datacenter or rack. * Each data has a name and its location in the network is * decided by a string with syntax similar to a file name. * For example, a data node's name is hostname:port# and if it's located at * rack "orange" in datacenter "dog", the string representation of its * network location is /dog/orange */ @Beta public interface Node { /** @return the string representation of this node's network location at the specified level in the hierarchy*/ String getNetworkLocation(int level); /** @return the string representation of this node's network location */ String getNetworkLocation(); /** * Set this node's network location. * @param location the location */ void setNetworkLocation(String location); /** @return this node's name */ String getName(); /** @return this node's parent */ Node getParent(); /** * Set this node's parent. * @param parent the parent */ void setParent(Node parent); /** @return this node's level in the tree. * E.g. the root of a tree returns 0 and its children return 1 */ int getLevel(); /** * Set this node's level in the tree. * @param i the level */ void setLevel(int i); }
58
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/AbstractDNSToSwitchMapping.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.net; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.bookkeeper.conf.Configurable; import org.apache.bookkeeper.proto.BookieAddressResolver; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; /** * This is a base class for DNS to Switch mappings. * * <p>It is not mandatory to derive {@link DNSToSwitchMapping} implementations from it, but it is strongly * recommended, as it makes it easy for the Hadoop developers to add new methods * to this base class that are automatically picked up by all implementations. * * <p>This class does not extend the <code>Configured</code> * base class, and should not be changed to do so, as it causes problems * for subclasses. The constructor of the <code>Configured</code> calls * the {@link #setConf(Configuration)} method, which will call into the * subclasses before they have been fully constructed. * */ public abstract class AbstractDNSToSwitchMapping implements DNSToSwitchMapping, Configurable { private Configuration conf; private BookieAddressResolver bookieAddressResolver; /** * Create an unconfigured instance. */ protected AbstractDNSToSwitchMapping() { } /** * Create an instance, caching the configuration file. * This constructor does not call {@link #setConf(Configuration)}; if * a subclass extracts information in that method, it must call it explicitly. * @param conf the configuration */ protected AbstractDNSToSwitchMapping(Configuration conf) { this.conf = conf; } public BookieAddressResolver getBookieAddressResolver() { return bookieAddressResolver; } @Override public void setBookieAddressResolver(BookieAddressResolver bookieAddressResolver) { this.bookieAddressResolver = bookieAddressResolver; } @Override public Configuration getConf() { return conf; } @Override public void setConf(Configuration conf) { this.conf = conf; validateConf(); } /** * Predicate that indicates that the switch mapping is known to be * single-switch. The base class returns false: it assumes all mappings are * multi-rack. Subclasses may override this with methods that are more aware * of their topologies. * * <p>This method is used when parts of Hadoop need know whether to apply * single rack vs multi-rack policies, such as during block placement. * Such algorithms behave differently if they are on multi-switch systems. * * @return true if the mapping thinks that it is on a single switch */ public boolean isSingleSwitch() { return false; } /** * Get a copy of the map (for diagnostics). * @return a clone of the map or null for none known */ public Map<String, String> getSwitchMap() { return null; } /** * Generate a string listing the switch mapping implementation, * the mapping for every known node and the number of nodes and * unique switches known about -each entry to a separate line. * @return a string that can be presented to the ops team or used in * debug messages. */ public String dumpTopology() { Map<String, String> rack = getSwitchMap(); StringBuilder builder = new StringBuilder(); builder.append("Mapping: ").append(this).append("\n"); if (rack != null) { builder.append("Map:\n"); Set<String> switches = new HashSet<String>(); for (Map.Entry<String, String> entry : rack.entrySet()) { builder.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\n"); switches.add(entry.getValue()); } builder.append("Nodes: ").append(rack.size()).append("\n"); builder.append("Switches: ").append(switches.size()).append("\n"); } else { builder.append("No topology information"); } return builder.toString(); } protected boolean isSingleSwitchByScriptPolicy() { return conf != null && (!StringUtils.isNotBlank(conf.getString(CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY))); } /** * Query for a {@link DNSToSwitchMapping} instance being on a single * switch. * * <p>This predicate simply assumes that all mappings not derived from * this class are multi-switch. * * @param mapping the mapping to query * @return true if the base class says it is single switch, or the mapping * is not derived from this class. */ public static boolean isMappingSingleSwitch(DNSToSwitchMapping mapping) { return mapping != null && mapping instanceof AbstractDNSToSwitchMapping && ((AbstractDNSToSwitchMapping) mapping).isSingleSwitch(); } /** * when setConf is called it should do sanity checking of the conf/env. and * throw RuntimeException if things are not valid. */ protected void validateConf() { } }
59
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/BookieSocketAddress.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.net; import static org.apache.bookkeeper.util.BookKeeperConstants.COLON; import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.net.InetAddresses; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.Optional; import org.apache.bookkeeper.proto.BookieAddressResolver; /** * This is a data wrapper class that is an InetSocketAddress, it would use the hostname * provided in constructors directly. * * <p>The string representation of a BookieSocketAddress is : &lt;hostname&gt;:&lt;port&gt; */ public class BookieSocketAddress { // Member fields that make up this class. private final String hostname; private final int port; private final Optional<InetSocketAddress> socketAddress; // Constructor that takes in both a port. public BookieSocketAddress(String hostname, int port) { this.hostname = hostname; this.port = port; /* * if ipaddress is used for bookieid then lets cache InetSocketAddress * otherwise not cache it. If Hostname is used for bookieid, then it is * ok for node to change its ipaddress. But if ipaddress is used for * bookieid then it is invalid scenario if node's ipaddress changes and * nodes HostName is considered static. */ if (InetAddresses.isInetAddress(hostname)) { socketAddress = Optional.of(new InetSocketAddress(hostname, port)); } else { socketAddress = Optional.empty(); } } // Constructor from a String "serialized" version of this class. public BookieSocketAddress(String addr) throws UnknownHostException { String[] parts = addr.split(COLON); if (parts.length < 2) { throw new UnknownHostException(addr); } this.hostname = parts[0]; try { this.port = Integer.parseInt(parts[1]); } catch (NumberFormatException nfe) { throw new UnknownHostException(addr); } if (InetAddresses.isInetAddress(hostname)) { socketAddress = Optional.of(new InetSocketAddress(hostname, port)); } else { socketAddress = Optional.empty(); } } // Public getters public String getHostName() { return hostname; } public int getPort() { return port; } // Method to return an InetSocketAddress for the regular port. @JsonIgnore public InetSocketAddress getSocketAddress() { /* * Return each time a new instance of the InetSocketAddress if hostname * is used as bookieid. If we keep using the same InetSocketAddress * instance, if bookies are advertising hostnames and the IP change, the * BK client will keep forever to try to connect to the old IP. */ return socketAddress.orElseGet(() -> { return new InetSocketAddress(hostname, port); }); } // Return the String "serialized" version of this object. @Override public String toString() { return hostname + COLON + port; } // Implement an equals method comparing two BookiSocketAddress objects. @Override public boolean equals(Object obj) { if (!(obj instanceof BookieSocketAddress)) { return false; } BookieSocketAddress that = (BookieSocketAddress) obj; return this.hostname.equals(that.hostname) && (this.port == that.port); } @Override public int hashCode() { return this.hostname.hashCode() + 13 * this.port; } /** * Create a BookieID in legacy format hostname:port. * @return the BookieID */ public BookieId toBookieId() { return BookieId.parse(this.toString()); } /** * Simple converter from legacy BookieId to a real network address. */ public static final BookieAddressResolver LEGACY_BOOKIEID_RESOLVER = (BookieId b) -> { try { return new BookieSocketAddress(b.toString()); } catch (UnknownHostException err) { throw new BookieAddressResolver.BookieIdNotResolvedException(b, err); } }; /** * Utility for Placement Policies that need to create a dummy BookieId that represents * a given host. * @param hostname the hostname * @return a dummy bookie id, compatible with the BookieSocketAddress#toBookieId, with a 0 tcp port. */ public static BookieId createDummyBookieIdForHostname(String hostname) { return BookieId.parse(hostname + ":0"); } /** * Tells whether a BookieId may be a dummy id. * @param bookieId * @return true if the BookieId looks like it has been generated by * {@link #createDummyBookieIdForHostname(java.lang.String)} */ public static boolean isDummyBookieIdForHostname(BookieId bookieId) { return bookieId.getId().endsWith(":0"); } /** * Use legacy resolver to resolve a bookieId. * @param bookieId legacy style bookie ID consisting of address (or hostname) and port * @return the BookieSocketAddress */ public static BookieSocketAddress resolveLegacyBookieId(BookieId bookieId) throws BookieAddressResolver.BookieIdNotResolvedException { return LEGACY_BOOKIEID_RESOLVER.resolve(bookieId); } }
60
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/CommonConfigurationKeys.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.net; /** * Common Configuration Keys. */ public interface CommonConfigurationKeys { // script file name to resolve network topology String NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY = "networkTopologyScriptFileName"; // number of arguments that network topology resolve script used String NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_KEY = "networkTopologyScriptNumberArgs"; // default value of NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_KEY int NET_TOPOLOGY_SCRIPT_NUMBER_ARGS_DEFAULT = 100; }
61
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/BookieId.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.net; import java.util.Objects; /** * This is an identifier for a BookieID. */ public final class BookieId { private final String id; private BookieId(String id) { validateBookieId(id); this.id = id; } /** * Returns the serialized version of this object. * @return the bookieId */ @Override public String toString() { return id; } /** * Parses the given serialized representation of a BookieId. * @param serialized * @return the parsed BookieId */ public static BookieId parse(String serialized) { return new BookieId(serialized); } public String getId() { return id; } @Override public int hashCode() { return this.id.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final BookieId other = (BookieId) obj; if (!Objects.equals(this.id, other.id)) { return false; } return true; } private static void validateBookieId(String id) { Objects.requireNonNull(id, "BookieId cannot be null"); if (!(id.matches("[a-zA-Z0-9:-_.\\-]+")) || "readonly".equalsIgnoreCase(id)) { throw new IllegalArgumentException("BookieId " + id + " is not valid"); } } }
62
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/NetworkTopology.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.net; import java.util.Collection; import java.util.Set; /** * Network Topology Interface. */ public interface NetworkTopology { String DEFAULT_REGION = "/default-region"; String DEFAULT_RACK = "/default-rack"; String DEFAULT_ZONE = "/default-zone"; String DEFAULT_UPGRADEDOMAIN = "/default-upgradedomain"; String DEFAULT_ZONE_AND_UPGRADEDOMAIN = DEFAULT_ZONE + DEFAULT_UPGRADEDOMAIN; String DEFAULT_REGION_AND_RACK = DEFAULT_REGION + DEFAULT_RACK; /** * Add a node to the network topology. * * @param node * add the node to network topology */ void add(Node node); /** * Remove a node from nework topology. * * @param node * remove the node from network topology */ void remove(Node node); /** * Check if the tree contains node <i>node</i>. * * @param node * node to check * @return true if <i>node</i> is already in the network topology, otherwise false. */ boolean contains(Node node); /** * Retrieve a node from the network topology. * @param loc * @return */ Node getNode(String loc); /** * Returns number of racks in the network topology. * * @return number of racks in the network topology. */ int getNumOfRacks(); /** * Returns the nodes under a location. * * @param loc * network location * @return nodes under a location */ Set<Node> getLeaves(String loc); /** * Return the number of leaves in <i>scope</i> but not in <i>excludedNodes</i>. * * <p>If scope starts with ~, return the number of nodes that are not * in <i>scope</i> and <i>excludedNodes</i>; * @param scope a path string that may start with ~ * @param excludedNodes a list of nodes * @return number of available nodes */ int countNumOfAvailableNodes(String scope, Collection<Node> excludedNodes); }
63
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/NetUtils.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.net; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * Network Utilities. */ public class NetUtils { /** * Given a string representation of a host, return its ip address * in textual presentation. * * @param name a string representation of a host: * either a textual representation its IP address or its host name * @return its IP address in the string format */ public static String normalizeHostName(String name) { try { return InetAddress.getByName(name).getHostAddress(); } catch (UnknownHostException e) { return name; } } /** * Given a collection of string representation of hosts, return a list of * corresponding IP addresses in the textual representation. * * @param names a collection of string representations of hosts * @return a list of corresponding IP addresses in the string format * @see #normalizeHostName(String) */ public static List<String> normalizeHostNames(Collection<String> names) { List<String> hostNames = new ArrayList<String>(names.size()); for (String name : names) { hostNames.add(normalizeHostName(name)); } return hostNames; } public static String resolveNetworkLocation(DNSToSwitchMapping dnsResolver, BookieSocketAddress addr) { List<String> names = new ArrayList<String>(1); InetSocketAddress inetSocketAddress = addr.getSocketAddress(); if (dnsResolver.useHostName()) { names.add(addr.getHostName()); } else { InetAddress inetAddress = inetSocketAddress.getAddress(); if (null == inetAddress) { names.add(addr.getHostName()); } else { names.add(inetAddress.getHostAddress()); } } // resolve network addresses List<String> rNames = dnsResolver.resolve(names); checkNotNull(rNames, "DNS Resolver should not return null response."); checkState(rNames.size() == 1, "Expected exactly one element"); return rNames.get(0); } }
64
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/DNS.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. */ // This code has been copied from hadoop-common 2.0.4-alpha package org.apache.bookkeeper.net; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Collections; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Vector; import javax.naming.NamingException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class that provides direct and reverse lookup functionalities, allowing * the querying of specific network interfaces or nameservers. */ public class DNS { private static final Logger LOG = LoggerFactory.getLogger(DNS.class); /** * The cached hostname -initially null. */ private static final String cachedHostname = resolveLocalHostname(); private static final String cachedHostAddress = resolveLocalHostIPAddress(); private static final String LOCALHOST = "localhost"; /** * Returns the hostname associated with the specified IP address by the * provided nameserver. * <p/> * Loopback addresses * * @param hostIp The address to reverse lookup * @param ns The host name of a reachable DNS server * @return The host name associated with the provided IP * @throws NamingException If a NamingException is encountered */ public static String reverseDns(InetAddress hostIp, String ns) throws NamingException { // // Builds the reverse IP lookup form // This is formed by reversing the IP numbers and appending in-addr.arpa // String[] parts = hostIp.getHostAddress().split("\\."); if (parts.length != 4) { //Not proper address. May be IPv6 throw new NamingException("IPV6"); } String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa"; DirContext ictx = new InitialDirContext(); Attributes attribute; try { attribute = ictx.getAttributes("dns://" // Use "dns:///" if the default + ((ns == null) ? "" : ns) // nameserver is to be used + "/" + reverseIP, new String[]{"PTR"}); } finally { ictx.close(); } if (null == attribute) { throw new NamingException("No attribute is found"); } Attribute ptrAttr = attribute.get("PTR"); if (null == ptrAttr) { throw new NamingException("No PTR attribute is found"); } if (null == ptrAttr.get()) { throw new NamingException("PTR attribute value is null"); } return ptrAttr.get().toString(); } /** * @return NetworkInterface for the given subinterface name (eg eth0:0) * or null if no interface with the given name can be found */ private static NetworkInterface getSubinterface(String strInterface) throws SocketException { Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces(); while (nifs.hasMoreElements()) { Enumeration<NetworkInterface> subNifs = nifs.nextElement().getSubInterfaces(); while (subNifs.hasMoreElements()) { NetworkInterface nif = subNifs.nextElement(); if (nif.getName().equals(strInterface)) { return nif; } } } return null; } /** * @param nif network interface to get addresses for * @return set containing addresses for each subinterface of nif, * see below for the rationale for using an ordered set */ private static LinkedHashSet<InetAddress> getSubinterfaceInetAddrs( NetworkInterface nif) { LinkedHashSet<InetAddress> addrs = new LinkedHashSet<InetAddress>(); Enumeration<NetworkInterface> subNifs = nif.getSubInterfaces(); while (subNifs.hasMoreElements()) { NetworkInterface subNif = subNifs.nextElement(); addrs.addAll(Collections.list(subNif.getInetAddresses())); } return addrs; } /** * Like {@link DNS#getIPs(String, boolean)}, but returns all * IPs associated with the given interface and its subinterfaces. */ public static String[] getIPs(String strInterface) throws UnknownHostException { return getIPs(strInterface, true); } /** * Returns all the IPs associated with the provided interface, if any, in * textual form. * * @param strInterface The name of the network interface or sub-interface to query * (eg eth0 or eth0:0) or the string "default" * @param returnSubinterfaces Whether to return IPs associated with subinterfaces of * the given interface * @return A string vector of all the IPs associated with the provided * interface. The local host IP is returned if the interface * name "default" is specified or there is an I/O error looking * for the given interface. * @throws UnknownHostException If the given interface is invalid */ public static String[] getIPs(String strInterface, boolean returnSubinterfaces) throws UnknownHostException { if ("default".equals(strInterface)) { return new String[]{cachedHostAddress}; } NetworkInterface netIf; try { netIf = NetworkInterface.getByName(strInterface); if (netIf == null) { netIf = getSubinterface(strInterface); } } catch (SocketException e) { LOG.warn("I/O error finding interface {}: {}", strInterface, e.getMessage()); return new String[]{cachedHostAddress}; } if (netIf == null) { throw new UnknownHostException("No such interface " + strInterface); } // NB: Using a LinkedHashSet to preserve the order for callers // that depend on a particular element being 1st in the array. // For example, getDefaultIP always returns the first element. LinkedHashSet<InetAddress> allAddrs = new LinkedHashSet<InetAddress>(); allAddrs.addAll(Collections.list(netIf.getInetAddresses())); if (!returnSubinterfaces) { allAddrs.removeAll(getSubinterfaceInetAddrs(netIf)); } String[] ips = new String[allAddrs.size()]; int i = 0; for (InetAddress addr : allAddrs) { ips[i++] = addr.getHostAddress(); } return ips; } /** * Returns the first available IP address associated with the provided * network interface or the local host IP if "default" is given. * * @param strInterface The name of the network interface or subinterface to query * (e.g. eth0 or eth0:0) or the string "default" * @return The IP address in text form, the local host IP is returned * if the interface name "default" is specified * @throws UnknownHostException If the given interface is invalid */ public static String getDefaultIP(String strInterface) throws UnknownHostException { String[] ips = getIPs(strInterface); return ips[0]; } /** * Returns all the host names associated by the provided nameserver with the * address bound to the specified network interface. * * @param strInterface The name of the network interface or subinterface to query * (e.g. eth0 or eth0:0) * @param nameserver The DNS host name * @return A string vector of all host names associated with the IPs tied to * the specified interface * @throws UnknownHostException if the given interface is invalid */ public static String[] getHosts(String strInterface, String nameserver) throws UnknownHostException { String[] ips = getIPs(strInterface); Vector<String> hosts = new Vector<String>(); for (int ctr = 0; ctr < ips.length; ctr++) { try { hosts.add(reverseDns(InetAddress.getByName(ips[ctr]), nameserver)); } catch (UnknownHostException ignored) { } catch (NamingException ignored) { } } if (hosts.isEmpty()) { LOG.warn("Unable to determine hostname for interface " + strInterface); return new String[]{cachedHostname}; } else { return hosts.toArray(new String[hosts.size()]); } } /** * Determine the local hostname; retrieving it from cache if it is known * If we cannot determine our host name, return "localhost". * * @return the local hostname or "localhost" */ private static String resolveLocalHostname() { String localhost; try { localhost = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { LOG.warn("Unable to determine local hostname " + "-falling back to \"" + LOCALHOST + "\"", e); localhost = LOCALHOST; } return localhost; } /** * Get the IPAddress of the local host as a string. * This will be a loop back value if the local host address cannot be * determined. * If the loopback address of "localhost" does not resolve, then the system's * network is in such a state that nothing is going to work. A message is * logged at the error level and a null pointer returned, a pointer * which will trigger failures later on the application * * @return the IPAddress of the local host or null for a serious problem. */ private static String resolveLocalHostIPAddress() { String address; try { address = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { LOG.warn("Unable to determine address of the host" + "-falling back to \"" + LOCALHOST + "\" address", e); try { address = InetAddress.getByName(LOCALHOST).getHostAddress(); } catch (UnknownHostException noLocalHostAddressException) { //at this point, deep trouble LOG.error("Unable to determine local loopback address " + "of \"" + LOCALHOST + "\" " + "-this system's network configuration is unsupported", e); address = null; } } return address; } /** * Returns all the host names associated by the default nameserver with the * address bound to the specified network interface. * * @param strInterface The name of the network interface to query (e.g. eth0) * @return The list of host names associated with IPs bound to the network * interface * @throws UnknownHostException If one is encountered while querying the default interface */ public static String[] getHosts(String strInterface) throws UnknownHostException { return getHosts(strInterface, null); } /** * Returns the default (first) host name associated by the provided * nameserver with the address bound to the specified network interface. * * @param strInterface The name of the network interface to query (e.g. eth0) * @param nameserver The DNS host name * @return The default host names associated with IPs bound to the network * interface * @throws UnknownHostException If one is encountered while querying the default interface */ public static String getDefaultHost(String strInterface, String nameserver) throws UnknownHostException { if ("default".equals(strInterface)) { return cachedHostname; } if ("default".equals(nameserver)) { return getDefaultHost(strInterface); } String[] hosts = getHosts(strInterface, nameserver); return hosts[0]; } /** * Returns the default (first) host name associated by the default * nameserver with the address bound to the specified network interface. * * @param strInterface The name of the network interface to query (e.g. eth0). * Must not be null. * @return The default host name associated with IPs bound to the network * interface * @throws UnknownHostException If one is encountered while querying the default interface */ public static String getDefaultHost(String strInterface) throws UnknownHostException { return getDefaultHost(strInterface, null); } }
65
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/NetworkTopologyImpl.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.net; import com.google.common.base.Strings; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The class represents a cluster of computer with a tree hierarchical * network topology. * For example, a cluster may be consists of many data centers filled * with racks of computers. * In a network topology, leaves represent data nodes (computers) and inner * nodes represent switches/routers that manage traffic in/out of data centers * or racks. * */ public class NetworkTopologyImpl implements NetworkTopology { public static final int DEFAULT_HOST_LEVEL = 2; public static final Logger LOG = LoggerFactory.getLogger(NetworkTopologyImpl.class); public static final String NODE_SEPARATOR = ","; public static final String INVERSE = "~"; /** * A marker for an InvalidTopology Exception. */ public static class InvalidTopologyException extends RuntimeException { private static final long serialVersionUID = 1L; public InvalidTopologyException(String msg) { super(msg); } } /** InnerNode represents a switch/router of a data center or rack. * Different from a leaf node, it has non-null children. */ static class InnerNode extends NodeBase { protected List<Node> children = new ArrayList<Node>(); private int numOfLeaves; /** * Construct an InnerNode from a path-like string. */ InnerNode(String path) { super(path); } /** * Construct an InnerNode from its name and its network location. */ InnerNode(String name, String location) { super(name, location); } /** * Construct an InnerNode from its name, its network location, its parent, and its level. */ InnerNode(String name, String location, InnerNode parent, int level) { super(name, location, parent, level); } /** * @return its children */ List<Node> getChildren() { return children; } /** * @return the number of children this node has */ int getNumOfChildren() { return children.size(); } /** * Judge if this node represents a rack. * @return true if it has no child or its children are not InnerNodes */ boolean isRack() { if (children.isEmpty()) { return true; } Node firstChild = children.get(0); return !(firstChild instanceof InnerNode); } /** * Judge if this node is an ancestor of node <i>n</i>. * * @param n a node * @return true if this node is an ancestor of <i>n</i> */ boolean isAncestor(Node n) { return !Strings.isNullOrEmpty(n.getNetworkLocation()) && (getPath(this).equals(NodeBase.PATH_SEPARATOR_STR) || (n.getNetworkLocation() + NodeBase.PATH_SEPARATOR_STR).startsWith(getPath(this) + NodeBase.PATH_SEPARATOR_STR)); } /** * Judge if this node is the parent of node <i>n</i>. * * @param n a node * @return true if this node is the parent of <i>n</i> */ boolean isParent(Node n) { return n.getNetworkLocation().equals(getPath(this)); } /** * Return a child name of this node who is an ancestor of node <i>n</i>. */ private String getNextAncestorName(Node n) { if (!isAncestor(n)) { throw new IllegalArgumentException(this + "is not an ancestor of " + n); } String name = n.getNetworkLocation().substring(getPath(this).length()); if (name.charAt(0) == PATH_SEPARATOR) { name = name.substring(1); } int index = name.indexOf(PATH_SEPARATOR); if (index != -1) { name = name.substring(0, index); } return name; } /** * Add node <i>n</i> to the subtree of this node. * @param n node to be added * @return true if the node is added; false otherwise */ boolean add(Node n) { if (!isAncestor(n)) { throw new IllegalArgumentException(n.getName() + ", which is located at " + n.getNetworkLocation() + ", is not a decendent of " + getPath(this)); } if (isParent(n)) { // this node is the parent of n; add n directly n.setParent(this); n.setLevel(this.level + 1); for (int i = 0; i < children.size(); i++) { if (children.get(i).getName().equals(n.getName())) { children.set(i, n); return false; } } children.add(n); numOfLeaves++; return true; } else { // find the next ancestor node String parentName = getNextAncestorName(n); InnerNode parentNode = null; for (int i = 0; i < children.size(); i++) { if (children.get(i).getName().equals(parentName)) { parentNode = (InnerNode) children.get(i); break; } } if (parentNode == null) { // create a new InnerNode parentNode = createParentNode(parentName); children.add(parentNode); } // add n to the subtree of the next ancestor node if (parentNode.add(n)) { numOfLeaves++; return true; } else { return false; } } } /** * Creates a parent node to be added to the list of children. * Creates a node using the InnerNode four argument constructor specifying * the name, location, parent, and level of this node. * * <p>To be overridden in subclasses for specific InnerNode implementations, * as alternative to overriding the full {@link #add(Node)} method. * * @param parentName The name of the parent node * @return A new inner node * @see InnerNode#InnerNode(String, String, InnerNode, int) */ protected InnerNode createParentNode(String parentName) { return new InnerNode(parentName, getPath(this), this, this.getLevel() + 1); } /** * Remove node <i>n</i> from the subtree of this node. * @param n node to be deleted * @return true if the node is deleted; false otherwise */ boolean remove(Node n) { String parent = n.getNetworkLocation(); String currentPath = getPath(this); if (!isAncestor(n)) { throw new IllegalArgumentException(n.getName() + ", which is located at " + parent + ", is not a descendent of " + currentPath); } if (isParent(n)) { // this node is the parent of n; remove n directly for (int i = 0; i < children.size(); i++) { if (children.get(i).getName().equals(n.getName())) { children.remove(i); numOfLeaves--; n.setParent(null); return true; } } return false; } else { // find the next ancestor node: the parent node String parentName = getNextAncestorName(n); InnerNode parentNode = null; int i; for (i = 0; i < children.size(); i++) { if (children.get(i).getName().equals(parentName)) { parentNode = (InnerNode) children.get(i); break; } } if (parentNode == null) { return false; } // remove n from the parent node boolean isRemoved = parentNode.remove(n); // if the parent node has no children, remove the parent node too if (isRemoved) { if (parentNode.getNumOfChildren() == 0) { children.remove(i); } numOfLeaves--; } return isRemoved; } } // end of remove /** * Given a node's string representation, return a reference to the node. * @param loc string location of the form /rack/node * @return null if the node is not found or the childnode is there but * not an instance of {@link InnerNode} */ private Node getLoc(String loc) { if (loc == null || loc.length() == 0) { return this; } String[] path = loc.split(PATH_SEPARATOR_STR, 2); Node childnode = null; for (int i = 0; i < children.size(); i++) { if (children.get(i).getName().equals(path[0])) { childnode = children.get(i); } } if (childnode == null) { return null; // non-existing node } else if (path.length == 1) { return childnode; } else if (childnode instanceof InnerNode) { return ((InnerNode) childnode).getLoc(path[1]); } else { return null; } } /** * Get <i>leafIndex</i> leaf of this subtree * if it is not in the <i>excludedNode</i>. * * @param leafIndex an indexed leaf of the node * @param excludedNode an excluded node (can be null) * @return */ Node getLeaf(int leafIndex, Node excludedNode) { int count = 0; // check if the excluded node a leaf boolean isLeaf = excludedNode == null || !(excludedNode instanceof InnerNode); // calculate the total number of excluded leaf nodes int numOfExcludedLeaves = isLeaf ? 1 : ((InnerNode) excludedNode).getNumOfLeaves(); if (isLeafParent()) { // children are leaves if (isLeaf) { // excluded node is a leaf node int excludedIndex = children.indexOf(excludedNode); if (excludedIndex != -1 && leafIndex >= 0) { // excluded node is one of the children so adjust the leaf index leafIndex = leafIndex >= excludedIndex ? leafIndex + 1 : leafIndex; } } // range check if (leafIndex < 0 || leafIndex >= this.getNumOfChildren()) { return null; } return children.get(leafIndex); } else { for (int i = 0; i < children.size(); i++) { InnerNode child = (InnerNode) children.get(i); if (excludedNode == null || excludedNode != child) { // not the excludedNode int numOfLeaves = child.getNumOfLeaves(); if (excludedNode != null && child.isAncestor(excludedNode)) { numOfLeaves -= numOfExcludedLeaves; } if (count + numOfLeaves > leafIndex) { // the leaf is in the child subtree return child.getLeaf(leafIndex - count, excludedNode); } else { // go to the next child count = count + numOfLeaves; } } else { // it is the excluededNode // skip it and set the excludedNode to be null excludedNode = null; } } return null; } } protected boolean isLeafParent() { return isRack(); } /** * Determine if children a leaves, default implementation calls {@link #isRack()}. * * <p>To be overridden in subclasses for specific InnerNode implementations, * as alternative to overriding the full {@link #getLeaf(int, Node)} method. * * @return true if children are leaves, false otherwise */ protected boolean areChildrenLeaves() { return isRack(); } /** * Get number of leaves. */ int getNumOfLeaves() { return numOfLeaves; } } // end of InnerNode /** * The root cluster map. */ InnerNode clusterMap; /** * Depth of all leaf nodes. */ private int depthOfAllLeaves = -1; /** * Rack counter. */ protected int numOfRacks = 0; /** * The lock used to manage access. */ protected ReadWriteLock netlock = new ReentrantReadWriteLock(); public NetworkTopologyImpl() { clusterMap = new InnerNode(InnerNode.ROOT); } /** * Add a leaf node. * Update node counter and rack counter if necessary * @param node node to be added; can be null * @exception IllegalArgumentException if add a node to a leave or node to be added is not a leaf */ @Override public void add(Node node) { if (node == null) { return; } String oldTopoStr = this.toString(); if (node instanceof InnerNode) { throw new IllegalArgumentException("Not allow to add an inner node: " + NodeBase.getPath(node)); } int newDepth = NodeBase.locationToDepth(node.getNetworkLocation()) + 1; netlock.writeLock().lock(); try { if ((depthOfAllLeaves != -1) && (depthOfAllLeaves != newDepth)) { LOG.error("Error: can't add leaf node {} at depth {} to topology:\n{}", node, newDepth, oldTopoStr); throw new InvalidTopologyException("Invalid network topology. " + "You cannot have a rack and a non-rack node at the same level of the network topology."); } Node rack = getNodeForNetworkLocation(node); if (rack != null && !(rack instanceof InnerNode)) { LOG.error("Unexpected data node {} at an illegal network location", node); throw new IllegalArgumentException("Unexpected data node " + node + " at an illegal network location"); } if (clusterMap.add(node)) { LOG.info("Adding a new node: " + NodeBase.getPath(node)); if (rack == null) { numOfRacks++; } if (!(node instanceof InnerNode)) { if (depthOfAllLeaves == -1) { depthOfAllLeaves = node.getLevel(); } } } if (LOG.isDebugEnabled()) { LOG.debug("NetworkTopology became:\n" + this); } } finally { netlock.writeLock().unlock(); } } /** * Return a reference to the node given its string representation. * Default implementation delegates to {@link #getNode(String)}. * * <p>To be overridden in subclasses for specific NetworkTopology * implementations, as alternative to overriding the full {@link #add(Node)} * method. * * @param node The string representation of this node's network location is * used to retrieve a Node object. * @return a reference to the node; null if the node is not in the tree * * @see #add(Node) * @see #getNode(String) */ protected Node getNodeForNetworkLocation(Node node) { return getNode(node.getNetworkLocation()); } /** * Given a string representation of a rack, return its children. * @param loc a path-like string representation of a rack * @return a newly allocated list with all the node's children */ public List<Node> getDatanodesInRack(String loc) { netlock.readLock().lock(); try { loc = NodeBase.normalize(loc); if (!NodeBase.ROOT.equals(loc)) { loc = loc.substring(1); } InnerNode rack = (InnerNode) clusterMap.getLoc(loc); if (rack == null) { return null; } return new ArrayList<Node>(rack.getChildren()); } finally { netlock.readLock().unlock(); } } /** * Remove a node. * Update node counter and rack counter if necessary. * * @param node node to be removed; can be null */ @Override public void remove(Node node) { if (node == null) { return; } else if (node instanceof InnerNode) { throw new IllegalArgumentException("Not allow to remove an inner node: " + NodeBase.getPath(node)); } LOG.info("Removing a node: " + NodeBase.getPath(node)); netlock.writeLock().lock(); try { if (clusterMap.remove(node)) { InnerNode rack = (InnerNode) getNode(node.getNetworkLocation()); if (rack == null) { numOfRacks--; } } if (LOG.isDebugEnabled()) { LOG.debug("NetworkTopology became:\n" + this); } } finally { netlock.writeLock().unlock(); } } /** * Check if the tree contains node <i>node</i>. * * @param node a node * @return true if <i>node</i> is already in the tree; false otherwise */ @Override public boolean contains(Node node) { if (node == null) { return false; } netlock.readLock().lock(); try { Node parent = node.getParent(); for (int level = node.getLevel(); parent != null && level > 0; parent = parent.getParent(), level--) { if (parent == clusterMap) { return true; } } } finally { netlock.readLock().unlock(); } return false; } /** * Given a string representation of a node, return its reference. * * @param loc * a path-like string representation of a node * @return a reference to the node; null if the node is not in the tree */ @Override public Node getNode(String loc) { netlock.readLock().lock(); try { loc = NodeBase.normalize(loc); if (!NodeBase.ROOT.equals(loc)) { loc = loc.substring(1); } return clusterMap.getLoc(loc); } finally { netlock.readLock().unlock(); } } /** * Given a string representation of a rack for a specific network location. * * <p>To be overridden in subclasses for specific NetworkTopology * implementations, as alternative to overriding the full * {@link #getRack(String)} method. * @param loc * a path-like string representation of a network location * @return a rack string */ public String getRack(String loc) { return loc; } /** @return the total number of racks */ @Override public int getNumOfRacks() { netlock.readLock().lock(); try { return numOfRacks; } finally { netlock.readLock().unlock(); } } /** @return the total number of leaf nodes */ public int getNumOfLeaves() { netlock.readLock().lock(); try { return clusterMap.getNumOfLeaves(); } finally { netlock.readLock().unlock(); } } /** * Return the distance between two nodes. * * <p>It is assumed that the distance from one node to its parent is 1 * The distance between two nodes is calculated by summing up their distances * to their closest common ancestor. * @param node1 one node * @param node2 another node * @return the distance between node1 and node2 which is zero if they are the same * or {@link Integer#MAX_VALUE} if node1 or node2 do not belong to the cluster */ public int getDistance(Node node1, Node node2) { if (node1 == node2) { return 0; } Node n1 = node1, n2 = node2; int dis = 0; netlock.readLock().lock(); try { int level1 = node1.getLevel(), level2 = node2.getLevel(); while (n1 != null && level1 > level2) { n1 = n1.getParent(); level1--; dis++; } while (n2 != null && level2 > level1) { n2 = n2.getParent(); level2--; dis++; } while (n1 != null && n2 != null && n1.getParent() != n2.getParent()) { n1 = n1.getParent(); n2 = n2.getParent(); dis += 2; } } finally { netlock.readLock().unlock(); } if (n1 == null) { LOG.warn("The cluster does not contain node: {}", NodeBase.getPath(node1)); return Integer.MAX_VALUE; } if (n2 == null) { LOG.warn("The cluster does not contain node: {}", NodeBase.getPath(node2)); return Integer.MAX_VALUE; } return dis + 2; } /** * Check if two nodes are on the same rack. * @param node1 one node (can be null) * @param node2 another node (can be null) * @return true if node1 and node2 are on the same rack; false otherwise * @exception IllegalArgumentException when either node1 or node2 is null, or * node1 or node2 do not belong to the cluster */ public boolean isOnSameRack(Node node1, Node node2) { if (node1 == null || node2 == null) { return false; } netlock.readLock().lock(); try { return isSameParents(node1, node2); } finally { netlock.readLock().unlock(); } } /** * Check if network topology is aware of NodeGroup. */ public boolean isNodeGroupAware() { return false; } /** * Return false directly as not aware of NodeGroup, to be override in sub-class. */ public boolean isOnSameNodeGroup(Node node1, Node node2) { return false; } /** * Compare the parents of each node for equality. * * <p>To be overridden in subclasses for specific NetworkTopology * implementations, as alternative to overriding the full * {@link #isOnSameRack(Node, Node)} method. * * @param node1 the first node to compare * @param node2 the second node to compare * @return true if their parents are equal, false otherwise * * @see #isOnSameRack(Node, Node) */ protected boolean isSameParents(Node node1, Node node2) { return node1.getParent() == node2.getParent(); } private static final Random r = new Random(); /** * Randomly choose one node from <i>scope</i>. * * <p>If scope starts with ~, choose one from the all nodes except for the * ones in <i>scope</i>; otherwise, choose one from <i>scope</i>. * @param scope range of nodes from which a node will be chosen * @return the chosen node */ public Node chooseRandom(String scope) { netlock.readLock().lock(); try { if (scope.startsWith(INVERSE)) { return chooseRandom(NodeBase.ROOT, scope.substring(1)); } else { return chooseRandom(scope, null); } } finally { netlock.readLock().unlock(); } } private Node chooseRandom(String scope, String excludedScope) { if (excludedScope != null) { if (scope.startsWith(excludedScope)) { return null; } if (!excludedScope.startsWith(scope)) { excludedScope = null; } } Node node = getNode(scope); if (!(node instanceof InnerNode)) { return node; } InnerNode innerNode = (InnerNode) node; int numOfDatanodes = innerNode.getNumOfLeaves(); if (excludedScope == null) { node = null; } else { node = getNode(excludedScope); if (!(node instanceof InnerNode)) { numOfDatanodes -= 1; } else { numOfDatanodes -= ((InnerNode) node).getNumOfLeaves(); } } int leaveIndex = r.nextInt(numOfDatanodes); return innerNode.getLeaf(leaveIndex, node); } /** * Return leaves in <i>scope</i>. * @param scope a path string * @return leaves nodes under specific scope */ private Set<Node> doGetLeaves(String scope) { Node node = getNode(scope); Set<Node> leafNodes = new HashSet<Node>(); if (node == null) { return leafNodes; } if (!(node instanceof InnerNode)) { leafNodes.add(node); } else { InnerNode innerNode = (InnerNode) node; for (int i = 0; i < innerNode.getNumOfLeaves(); i++) { leafNodes.add(innerNode.getLeaf(i, null)); } } return leafNodes; } @Override public Set<Node> getLeaves(String scope) { netlock.readLock().lock(); try { if (scope.startsWith(INVERSE)) { Set<Node> allNodes = doGetLeaves(NodeBase.ROOT); String[] excludeScopes = scope.substring(1).split(NODE_SEPARATOR); Set<Node> excludeNodes = new HashSet<Node>(); Arrays.stream(excludeScopes).forEach((excludeScope) -> { excludeNodes.addAll(doGetLeaves(excludeScope)); }); allNodes.removeAll(excludeNodes); return allNodes; } else { return doGetLeaves(scope); } } finally { netlock.readLock().unlock(); } } @Override public int countNumOfAvailableNodes(String scope, Collection<Node> excludedNodes) { boolean isExcluded = false; if (scope.startsWith(INVERSE)) { isExcluded = true; scope = scope.substring(1); } scope = NodeBase.normalize(scope); int count = 0; // the number of nodes in both scope & excludedNodes netlock.readLock().lock(); try { for (Node node : excludedNodes) { if ((NodeBase.getPath(node) + NodeBase.PATH_SEPARATOR_STR).startsWith(scope + NodeBase.PATH_SEPARATOR_STR)) { count++; } } Node n = getNode(scope); int scopeNodeCount = 0; if (n instanceof InnerNode) { scopeNodeCount = ((InnerNode) n).getNumOfLeaves(); } if (isExcluded) { return clusterMap.getNumOfLeaves() - scopeNodeCount - excludedNodes.size() + count; } else { return scopeNodeCount - count; } } finally { netlock.readLock().unlock(); } } /** * Convert a network tree to a string. */ @Override public String toString() { // print the number of racks StringBuilder tree = new StringBuilder(); tree.append("Number of racks: "); tree.append(numOfRacks); tree.append("\n"); // print the number of leaves int numOfLeaves = getNumOfLeaves(); tree.append("Expected number of leaves:"); tree.append(numOfLeaves); tree.append("\n"); // print nodes for (int i = 0; i < numOfLeaves; i++) { tree.append(NodeBase.getPath(clusterMap.getLeaf(i, null))); tree.append("\n"); } return tree.toString(); } /** * Divide networklocation string into two parts by last separator, and get * the first part here. * * @param networkLocation * @return */ public static String getFirstHalf(String networkLocation) { int index = networkLocation.lastIndexOf(NodeBase.PATH_SEPARATOR_STR); return networkLocation.substring(0, index); } /** * Divide networklocation string into two parts by last separator, and get * the second part here. * * @param networkLocation * @return */ public static String getLastHalf(String networkLocation) { int index = networkLocation.lastIndexOf(NodeBase.PATH_SEPARATOR_STR); return networkLocation.substring(index); } /** * Swap two array items. */ protected static void swap(Node[] nodes, int i, int j) { Node tempNode; tempNode = nodes[j]; nodes[j] = nodes[i]; nodes[i] = tempNode; } /** Sort nodes array by their distances to <i>reader</i> * It linearly scans the array, if a local node is found, swap it with * the first element of the array. * If a local rack node is found, swap it with the first element following * the local node. * If neither local node or local rack node is found, put a random replica * location at position 0. * It leaves the rest nodes untouched. * @param reader the node that wishes to read a block from one of the nodes * @param nodes the list of nodes containing data for the reader */ public void pseudoSortByDistance(Node reader, Node[] nodes) { int tempIndex = 0; int localRackNode = -1; if (reader != null) { //scan the array to find the local node & local rack node for (int i = 0; i < nodes.length; i++) { if (tempIndex == 0 && reader == nodes[i]) { //local node //swap the local node and the node at position 0 if (i != 0) { swap(nodes, tempIndex, i); } tempIndex = 1; if (localRackNode != -1) { if (localRackNode == 0) { localRackNode = i; } break; } } else if (localRackNode == -1 && isOnSameRack(reader, nodes[i])) { //local rack localRackNode = i; if (tempIndex != 0) { break; } } } // swap the local rack node and the node at position tempIndex if (localRackNode != -1 && localRackNode != tempIndex) { swap(nodes, tempIndex, localRackNode); tempIndex++; } } // put a random node at position 0 if it is not a local/local-rack node if (tempIndex == 0 && localRackNode == -1 && nodes.length != 0) { swap(nodes, 0, r.nextInt(nodes.length)); } } }
66
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/DNSToSwitchMapping.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.net; import com.google.common.annotations.Beta; import java.util.List; import org.apache.bookkeeper.proto.BookieAddressResolver; /** * An interface that must be implemented to allow pluggable * DNS-name/IP-address to RackID resolvers. * */ @Beta public interface DNSToSwitchMapping { /** * Resolves a list of DNS-names/IP-addresses and returns back a list of * switch information (network paths). One-to-one correspondence must be * maintained between the elements in the lists. * Consider an element in the argument list - x.y.com. The switch information * that is returned must be a network path of the form /foo/rack, * where / is the root, and 'foo' is the switch where 'rack' is connected. * Note the hostname/ip-address is not part of the returned path. * The network topology of the cluster would determine the number of * components in the network path. * * <p>If a name cannot be resolved to a rack, the implementation * should return {@link NetworkTopology#DEFAULT_REGION_AND_RACK}. This * is what the bundled implementations do, though it is not a formal requirement * * @param names the list of hosts to resolve (can be empty) * @return list of resolved network paths. * If <i>names</i> is empty, the returned list is also empty */ List<String> resolve(List<String> names); /** * Reload all of the cached mappings. * * <p>If there is a cache, this method will clear it, so that future accesses * will get a chance to see the new data. */ void reloadCachedMappings(); /** * Hints what to use with implementation when InetSocketAddress is converted * to String: * hostname (addr.getHostName(), default) * or IP address (addr.getAddress().getHostAddress()). * @return true if hostname, false if IP address. Default is true. */ default boolean useHostName() { return true; } /** * Receives the current BookieAddressResolver. * @param bookieAddressResolver */ default void setBookieAddressResolver(BookieAddressResolver bookieAddressResolver) { } }
67
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/BookieNode.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.net; /** * Bookie Node implementation. */ public class BookieNode extends NodeBase { private final BookieId addr; // identifier of a bookie node. public BookieNode(BookieId addr, String networkLoc) { super(addr.toString(), networkLoc); this.addr = addr; } public BookieId getAddr() { return addr; } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object obj) { if (!(obj instanceof BookieNode)) { return false; } BookieNode other = (BookieNode) obj; return getName().equals(other.getName()); } @Override public String toString() { return String.format("<Bookie:%s>", name); } }
68
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/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. */ /** * Network-related classes. */ package org.apache.bookkeeper.net;
69
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/net/NodeBase.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.net; /** * A base class that implements interface Node. */ public class NodeBase implements Node { /** * Path separator {@value}. */ public static final char PATH_SEPARATOR = '/'; /** * Path separator as a string {@value}. */ public static final String PATH_SEPARATOR_STR = "/"; /** * String representation of root {@value}. */ public static final String ROOT = ""; protected String name; //host:port# protected String location; //string representation of this node's location protected int level; //which level of the tree the node resides protected Node parent; //its parent /** * Default constructor. */ public NodeBase() { } /** * Construct a node from its path. * @param path * a concatenation of this node's location, the path seperator, and its name */ public NodeBase(String path) { path = normalize(path); int index = path.lastIndexOf(PATH_SEPARATOR); if (index == -1) { set(ROOT, path); } else { set(path.substring(index + 1), path.substring(0, index)); } } /** * Construct a node from its name and its location. * @param name this node's name (can be null, must not contain {@link #PATH_SEPARATOR}) * @param location this node's location */ public NodeBase(String name, String location) { set(name, normalize(location)); } /** * Construct a node from its name and its location. * @param name this node's name (can be null, must not contain {@link #PATH_SEPARATOR}) * @param location this node's location * @param parent this node's parent node * @param level this node's level in the tree */ public NodeBase(String name, String location, Node parent, int level) { set(name, normalize(location)); this.parent = parent; this.level = level; } /** * Set this node's name and location. * @param name the (nullable) name -which cannot contain the {@link #PATH_SEPARATOR} * @param location the location */ private void set(String name, String location) { if (name != null && name.contains(PATH_SEPARATOR_STR)) { throw new IllegalArgumentException("Network location name contains /: " + name); } this.name = (name == null) ? "" : name; this.location = location; } /** @return this node's name */ @Override public String getName() { return name; } /** @return this node's network location */ @Override public String getNetworkLocation() { return location; } /** * Set this node's network location. * @param location the location */ @Override public void setNetworkLocation(String location) { this.location = location; } /** * Get the path of a node. * @param node a non-null node * @return the path of a node */ public static String getPath(Node node) { return node.getNetworkLocation() + PATH_SEPARATOR_STR + node.getName(); } /** @return this node's path as its string representation */ @Override public String toString() { return getPath(this); } /** * Normalize a path by stripping off any trailing {@link #PATH_SEPARATOR}. * @param path path to normalize. * @return the normalised path * If <i>path</i>is null or empty {@link #ROOT} is returned * @throws IllegalArgumentException if the first character of a non empty path * is not {@link #PATH_SEPARATOR} */ public static String normalize(String path) { if (path == null || path.length() == 0) { return ROOT; } if (path.charAt(0) != PATH_SEPARATOR) { throw new IllegalArgumentException("Network Location path does not start with " + PATH_SEPARATOR_STR + ": " + path); } int len = path.length(); if (path.charAt(len - 1) == PATH_SEPARATOR) { return path.substring(0, len - 1); } return path; } /** @return this node's parent */ @Override public Node getParent() { return parent; } /** * Set this node's parent. * @param parent the parent */ @Override public void setParent(Node parent) { this.parent = parent; } /** @return this node's level in the tree. * E.g. the root of a tree returns 0 and its children return 1 */ @Override public int getLevel() { return level; } /** * Set this node's level in the tree. * @param level the level */ @Override public void setLevel(int level) { this.level = level; } public static int locationToDepth(String location) { String normalizedLocation = normalize(location); int length = normalizedLocation.length(); int depth = 0; for (int i = 0; i < length; i++) { if (normalizedLocation.charAt(i) == PATH_SEPARATOR) { depth++; } } return depth; } @Override public String getNetworkLocation(int distanceFromLeaves) { Node node = this; while (distanceFromLeaves > 1) { Node parent = node.getParent(); if (null == parent) { break; } node = parent; distanceFromLeaves--; } return node.getNetworkLocation(); } }
70
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/AuthHandler.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.proto; import static org.apache.bookkeeper.auth.AuthProviderFactoryFactory.AUTHENTICATION_DISABLED_PLUGIN_NAME; import com.google.protobuf.ByteString; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelPromise; import java.io.IOException; import java.net.SocketAddress; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicLong; import org.apache.bookkeeper.auth.AuthCallbacks; import org.apache.bookkeeper.auth.AuthToken; import org.apache.bookkeeper.auth.BookieAuthProvider; import org.apache.bookkeeper.auth.ClientAuthProvider; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.proto.BookkeeperProtocol.AuthMessage; import org.apache.bookkeeper.util.ByteBufList; import org.apache.bookkeeper.util.NettyChannelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class AuthHandler { static final Logger LOG = LoggerFactory.getLogger(AuthHandler.class); static class ServerSideHandler extends ChannelInboundHandlerAdapter { volatile boolean authenticated = false; final BookieAuthProvider.Factory authProviderFactory; final BookieConnectionPeer connectionPeer; BookieAuthProvider authProvider; ServerSideHandler(BookieConnectionPeer connectionPeer, BookieAuthProvider.Factory authProviderFactory) { this.authProviderFactory = authProviderFactory; this.connectionPeer = connectionPeer; authProvider = null; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { authProvider = authProviderFactory.newProvider(connectionPeer, new AuthHandshakeCompleteCallback()); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (authProvider != null) { authProvider.close(); } super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (authProvider == null) { // close the channel, authProvider should only be // null if the other end of line is an InetSocketAddress // anything else is strange, and we don't want to deal // with it ctx.channel().close(); return; } if (authenticated) { super.channelRead(ctx, msg); } else if (msg instanceof BookieProtocol.AuthRequest) { // pre-PB-client BookieProtocol.AuthRequest req = (BookieProtocol.AuthRequest) msg; assert (req.getOpCode() == BookieProtocol.AUTH); if (checkAuthPlugin(req.getAuthMessage(), ctx.channel())) { byte[] payload = req .getAuthMessage() .getPayload() .toByteArray(); authProvider.process(AuthToken.wrap(payload), new AuthResponseCallbackLegacy(req, ctx.channel())); } else { ctx.channel().close(); } } else if (msg instanceof BookieProtocol.Request) { BookieProtocol.Request req = (BookieProtocol.Request) msg; if (req.getOpCode() == BookieProtocol.ADDENTRY) { final BookieProtocol.AddResponse response = BookieProtocol.AddResponse.create( req.getProtocolVersion(), BookieProtocol.EUA, req.getLedgerId(), req.getEntryId()); NettyChannelUtil.writeAndFlushWithVoidPromise(ctx.channel(), response); } else if (req.getOpCode() == BookieProtocol.READENTRY) { final BookieProtocol.ReadResponse response = new BookieProtocol.ReadResponse( req.getProtocolVersion(), BookieProtocol.EUA, req.getLedgerId(), req.getEntryId()); NettyChannelUtil.writeAndFlushWithVoidPromise(ctx.channel(), response); } else { ctx.channel().close(); } } else if (msg instanceof BookkeeperProtocol.Request) { // post-PB-client BookkeeperProtocol.Request req = (BookkeeperProtocol.Request) msg; if (req.getHeader().getOperation() == BookkeeperProtocol.OperationType.AUTH && req.hasAuthRequest() && checkAuthPlugin(req.getAuthRequest(), ctx.channel())) { byte[] payload = req .getAuthRequest() .getPayload() .toByteArray(); authProvider.process(AuthToken.wrap(payload), new AuthResponseCallback(req, ctx.channel(), authProviderFactory.getPluginName())); } else if (req.getHeader().getOperation() == BookkeeperProtocol.OperationType.START_TLS && req.hasStartTLSRequest()) { super.channelRead(ctx, msg); } else { BookkeeperProtocol.Response.Builder builder = BookkeeperProtocol.Response.newBuilder() .setHeader(req.getHeader()) .setStatus(BookkeeperProtocol.StatusCode.EUA); NettyChannelUtil.writeAndFlushWithVoidPromise(ctx.channel(), builder.build()); } } else { // close the channel, junk coming over it ctx.channel().close(); } } private boolean checkAuthPlugin(AuthMessage am, final Channel src) { if (!am.hasAuthPluginName() || !am.getAuthPluginName().equals(authProviderFactory.getPluginName())) { LOG.error("Received message from incompatible auth plugin. Local = {}, Remote = {}, Channel = {}", authProviderFactory.getPluginName(), am.getAuthPluginName(), src); return false; } return true; } public boolean isAuthenticated() { return authenticated; } static class AuthResponseCallbackLegacy implements AuthCallbacks.GenericCallback<AuthToken> { final BookieProtocol.AuthRequest req; final Channel channel; AuthResponseCallbackLegacy(BookieProtocol.AuthRequest req, Channel channel) { this.req = req; this.channel = channel; } @Override public void operationComplete(int rc, AuthToken newam) { if (rc != BKException.Code.OK) { LOG.error("Error processing auth message, closing connection"); channel.close(); return; } AuthMessage message = AuthMessage.newBuilder().setAuthPluginName(req.authMessage.getAuthPluginName()) .setPayload(ByteString.copyFrom(newam.getData())).build(); final BookieProtocol.AuthResponse response = new BookieProtocol.AuthResponse(req.getProtocolVersion(), message); NettyChannelUtil.writeAndFlushWithVoidPromise(channel, response); } } static class AuthResponseCallback implements AuthCallbacks.GenericCallback<AuthToken> { final BookkeeperProtocol.Request req; final Channel channel; final String pluginName; AuthResponseCallback(BookkeeperProtocol.Request req, Channel channel, String pluginName) { this.req = req; this.channel = channel; this.pluginName = pluginName; } @Override public void operationComplete(int rc, AuthToken newam) { BookkeeperProtocol.Response.Builder builder = BookkeeperProtocol.Response.newBuilder() .setHeader(req.getHeader()); if (rc != BKException.Code.OK) { LOG.error("Error processing auth message, closing connection"); builder.setStatus(BookkeeperProtocol.StatusCode.EUA); NettyChannelUtil.writeAndFlushWithClosePromise( channel, builder.build() ); return; } else { AuthMessage message = AuthMessage.newBuilder().setAuthPluginName(pluginName) .setPayload(ByteString.copyFrom(newam.getData())).build(); builder.setStatus(BookkeeperProtocol.StatusCode.EOK).setAuthResponse(message); NettyChannelUtil.writeAndFlushWithVoidPromise( channel, builder.build() ); } } } class AuthHandshakeCompleteCallback implements AuthCallbacks.GenericCallback<Void> { @Override public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { authenticated = true; LOG.info("Authentication success on server side"); } else { if (LOG.isDebugEnabled()) { LOG.debug("Authentication failed on server side"); } } } } } static class ClientSideHandler extends ChannelDuplexHandler { volatile boolean authenticated = false; final ClientAuthProvider.Factory authProviderFactory; ClientAuthProvider authProvider; final AtomicLong transactionIdGenerator; final Queue<Object> waitingForAuth = new ConcurrentLinkedQueue<>(); final ClientConnectionPeer connectionPeer; private final boolean isUsingV2Protocol; public ClientAuthProvider getAuthProvider() { return authProvider; } ClientSideHandler(ClientAuthProvider.Factory authProviderFactory, AtomicLong transactionIdGenerator, ClientConnectionPeer connectionPeer, boolean isUsingV2Protocol) { this.authProviderFactory = authProviderFactory; this.transactionIdGenerator = transactionIdGenerator; this.connectionPeer = connectionPeer; authProvider = null; this.isUsingV2Protocol = isUsingV2Protocol; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { authProvider = authProviderFactory.newProvider(connectionPeer, new AuthHandshakeCompleteCallback(ctx)); authProvider.init(new AuthRequestCallback(ctx, authProviderFactory.getPluginName())); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (authProvider != null) { authProvider.close(); } super.channelInactive(ctx); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { assert (authProvider != null); if (authenticated) { super.channelRead(ctx, msg); } else if (msg instanceof BookkeeperProtocol.Response) { BookkeeperProtocol.Response resp = (BookkeeperProtocol.Response) msg; if (null == resp.getHeader().getOperation()) { LOG.info("dropping received malformed message {} from bookie {}", msg, ctx.channel()); // drop the message without header } else { switch (resp.getHeader().getOperation()) { case START_TLS: super.channelRead(ctx, msg); break; case AUTH: if (resp.getStatus() != BookkeeperProtocol.StatusCode.EOK) { authenticationError(ctx, resp.getStatus().getNumber()); } else { assert (resp.hasAuthResponse()); BookkeeperProtocol.AuthMessage am = resp.getAuthResponse(); if (AUTHENTICATION_DISABLED_PLUGIN_NAME.equals(am.getAuthPluginName())){ SocketAddress remote = ctx.channel().remoteAddress(); LOG.info("Authentication is not enabled." + "Considering this client {} authenticated", remote); AuthHandshakeCompleteCallback cb = new AuthHandshakeCompleteCallback(ctx); cb.operationComplete(BKException.Code.OK, null); return; } byte[] payload = am.getPayload().toByteArray(); authProvider.process(AuthToken.wrap(payload), new AuthRequestCallback(ctx, authProviderFactory.getPluginName())); } break; default: LOG.warn("dropping received message {} from bookie {}", msg, ctx.channel()); // else just drop the message, // we're not authenticated so nothing should be coming through break; } } } else if (msg instanceof BookieProtocol.Response) { BookieProtocol.Response resp = (BookieProtocol.Response) msg; switch (resp.opCode) { case BookieProtocol.AUTH: if (resp.errorCode != BookieProtocol.EOK) { authenticationError(ctx, resp.errorCode); } else { BookkeeperProtocol.AuthMessage am = ((BookieProtocol.AuthResponse) resp).authMessage; if (AUTHENTICATION_DISABLED_PLUGIN_NAME.equals(am.getAuthPluginName())) { SocketAddress remote = ctx.channel().remoteAddress(); LOG.info("Authentication is not enabled." + "Considering this client {} authenticated", remote); AuthHandshakeCompleteCallback cb = new AuthHandshakeCompleteCallback(ctx); cb.operationComplete(BKException.Code.OK, null); return; } byte[] payload = am.getPayload().toByteArray(); authProvider.process(AuthToken.wrap(payload), new AuthRequestCallback(ctx, authProviderFactory.getPluginName())); } break; default: LOG.warn("dropping received message {} from bookie {}", msg, ctx.channel()); // else just drop the message, we're not authenticated so nothing should be coming // through break; } } } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { synchronized (this) { if (authenticated) { super.write(ctx, msg, promise); super.flush(ctx); } else if (msg instanceof BookkeeperProtocol.Request) { // let auth messages through, queue the rest BookkeeperProtocol.Request req = (BookkeeperProtocol.Request) msg; if (req.getHeader().getOperation() == BookkeeperProtocol.OperationType.AUTH || req.getHeader().getOperation() == BookkeeperProtocol.OperationType.START_TLS) { super.write(ctx, msg, promise); super.flush(ctx); } else { waitingForAuth.add(msg); } } else if (msg instanceof BookieProtocol.Request) { // let auth messages through, queue the rest BookieProtocol.Request req = (BookieProtocol.Request) msg; if (BookieProtocol.AUTH == req.getOpCode()) { super.write(ctx, msg, promise); super.flush(ctx); } else { waitingForAuth.add(msg); } } else if (msg instanceof ByteBuf || msg instanceof ByteBufList) { waitingForAuth.add(msg); } else { LOG.info("[{}] dropping write of message {}", ctx.channel(), msg); } } } long newTxnId() { return transactionIdGenerator.incrementAndGet(); } void authenticationError(ChannelHandlerContext ctx, int errorCode) { LOG.error("Error processing auth message, erroring connection {}", errorCode); ctx.fireExceptionCaught(new AuthenticationException("Auth failed with error " + errorCode)); } class AuthRequestCallback implements AuthCallbacks.GenericCallback<AuthToken> { Channel channel; ChannelHandlerContext ctx; String pluginName; AuthRequestCallback(ChannelHandlerContext ctx, String pluginName) { this.channel = ctx.channel(); this.ctx = ctx; this.pluginName = pluginName; } @Override public void operationComplete(int rc, AuthToken newam) { if (rc != BKException.Code.OK) { authenticationError(ctx, rc); return; } AuthMessage message = AuthMessage.newBuilder().setAuthPluginName(pluginName) .setPayload(ByteString.copyFrom(newam.getData())).build(); if (isUsingV2Protocol) { final BookieProtocol.AuthRequest msg = new BookieProtocol.AuthRequest(BookieProtocol.CURRENT_PROTOCOL_VERSION, message); NettyChannelUtil.writeAndFlushWithVoidPromise(channel, msg); } else { // V3 protocol BookkeeperProtocol.BKPacketHeader header = BookkeeperProtocol.BKPacketHeader.newBuilder() .setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE) .setOperation(BookkeeperProtocol.OperationType.AUTH).setTxnId(newTxnId()).build(); BookkeeperProtocol.Request.Builder builder = BookkeeperProtocol.Request.newBuilder() .setHeader(header) .setAuthRequest(message); NettyChannelUtil.writeAndFlushWithVoidPromise(channel, builder.build()); } } } class AuthHandshakeCompleteCallback implements AuthCallbacks.GenericCallback<Void> { ChannelHandlerContext ctx; AuthHandshakeCompleteCallback(ChannelHandlerContext ctx) { this.ctx = ctx; } @Override public void operationComplete(int rc, Void v) { if (rc == BKException.Code.OK) { synchronized (this) { authenticated = true; Object msg = waitingForAuth.poll(); while (msg != null) { NettyChannelUtil.writeAndFlushWithVoidPromise(ctx, msg); msg = waitingForAuth.poll(); } } } else { LOG.warn("Client authentication failed"); authenticationError(ctx, rc); } } } } @SuppressWarnings("serial") static class AuthenticationException extends IOException { AuthenticationException(String reason) { super(reason); } } }
71
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieRequestHandler.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.proto; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.group.ChannelGroup; import java.nio.channels.ClosedChannelException; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.processor.RequestProcessor; /** * Serverside handler for bookkeeper requests. */ @Slf4j public class BookieRequestHandler extends ChannelInboundHandlerAdapter { private static final int DEFAULT_PENDING_RESPONSE_SIZE = 256; private final RequestProcessor requestProcessor; private final ChannelGroup allChannels; private ChannelHandlerContext ctx; private ByteBuf pendingSendResponses = null; private int maxPendingResponsesSize = DEFAULT_PENDING_RESPONSE_SIZE; BookieRequestHandler(ServerConfiguration conf, RequestProcessor processor, ChannelGroup allChannels) { this.requestProcessor = processor; this.allChannels = allChannels; } public ChannelHandlerContext ctx() { return ctx; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { log.info("Channel connected {}", ctx.channel()); this.ctx = ctx; super.channelActive(ctx); } @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { allChannels.add(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { log.info("Channels disconnected: {}", ctx.channel()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { if (cause instanceof ClosedChannelException) { log.info("Client died before request could be completed on {}", ctx.channel(), cause); return; } log.error("Unhandled exception occurred in I/O thread or handler on {}", ctx.channel(), cause); ctx.close(); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (!(msg instanceof BookkeeperProtocol.Request || msg instanceof BookieProtocol.Request)) { ctx.fireChannelRead(msg); return; } requestProcessor.processRequest(msg, this); } public synchronized void prepareSendResponseV2(int rc, BookieProtocol.ParsedAddRequest req) { if (pendingSendResponses == null) { pendingSendResponses = ctx().alloc().directBuffer(maxPendingResponsesSize); } BookieProtoEncoding.ResponseEnDeCoderPreV3.serializeAddResponseInto(rc, req, pendingSendResponses); } public synchronized void flushPendingResponse() { if (pendingSendResponses != null) { maxPendingResponsesSize = (int) Math.max( maxPendingResponsesSize * 0.5 + 0.5 * pendingSendResponses.readableBytes(), DEFAULT_PENDING_RESPONSE_SIZE); if (ctx().channel().isActive()) { ctx().writeAndFlush(pendingSendResponses, ctx.voidPromise()); } else { pendingSendResponses.release(); } pendingSendResponses = null; } } }
72
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/GetListOfEntriesOfLedgerProcessorV3.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.proto; import com.google.protobuf.ByteString; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetListOfEntriesOfLedgerRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetListOfEntriesOfLedgerResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.util.AvailabilityOfEntriesOfLedger; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A processor class for v3 entries of a ledger packets. */ public class GetListOfEntriesOfLedgerProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(GetListOfEntriesOfLedgerProcessorV3.class); protected final GetListOfEntriesOfLedgerRequest getListOfEntriesOfLedgerRequest; protected final long ledgerId; public GetListOfEntriesOfLedgerProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); this.getListOfEntriesOfLedgerRequest = request.getGetListOfEntriesOfLedgerRequest(); this.ledgerId = getListOfEntriesOfLedgerRequest.getLedgerId(); } private GetListOfEntriesOfLedgerResponse getListOfEntriesOfLedgerResponse() { long startTimeNanos = MathUtils.nowInNano(); GetListOfEntriesOfLedgerResponse.Builder getListOfEntriesOfLedgerResponse = GetListOfEntriesOfLedgerResponse .newBuilder(); getListOfEntriesOfLedgerResponse.setLedgerId(ledgerId); if (!isVersionCompatible()) { getListOfEntriesOfLedgerResponse.setStatus(StatusCode.EBADVERSION); requestProcessor.getRequestStats().getGetListOfEntriesOfLedgerStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); return getListOfEntriesOfLedgerResponse.build(); } if (LOG.isDebugEnabled()) { LOG.debug("Received new getListOfEntriesOfLedger request: {}", request); } StatusCode status = StatusCode.EOK; AvailabilityOfEntriesOfLedger availabilityOfEntriesOfLedger = null; try { availabilityOfEntriesOfLedger = new AvailabilityOfEntriesOfLedger( requestProcessor.bookie.getListOfEntriesOfLedger(ledgerId)); getListOfEntriesOfLedgerResponse.setAvailabilityOfEntriesOfLedger( ByteString.copyFrom(availabilityOfEntriesOfLedger.serializeStateOfEntriesOfLedger())); } catch (Bookie.NoLedgerException e) { status = StatusCode.ENOLEDGER; LOG.error("No ledger found while performing getListOfEntriesOfLedger from ledger: {}", ledgerId, e); } catch (IOException e) { status = StatusCode.EIO; LOG.error("IOException while performing getListOfEntriesOfLedger from ledger: {}", ledgerId); } if (status == StatusCode.EOK) { requestProcessor.getRequestStats().getListOfEntriesOfLedgerStats .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getListOfEntriesOfLedgerStats .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } // Finally set the status and return getListOfEntriesOfLedgerResponse.setStatus(status); return getListOfEntriesOfLedgerResponse.build(); } @Override public void run() { GetListOfEntriesOfLedgerResponse listOfEntriesOfLedgerResponse = getListOfEntriesOfLedgerResponse(); Response.Builder response = Response.newBuilder().setHeader(getHeader()) .setStatus(listOfEntriesOfLedgerResponse.getStatus()) .setGetListOfEntriesOfLedgerResponse(listOfEntriesOfLedgerResponse); Response resp = response.build(); sendResponse(listOfEntriesOfLedgerResponse.getStatus(), resp, requestProcessor.getRequestStats().getListOfEntriesOfLedgerRequestStats); } }
73
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.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.proto; import static org.apache.bookkeeper.client.LedgerHandle.INVALID_ENTRY_ID; import com.google.common.base.Joiner; import com.google.common.collect.Sets; import com.google.protobuf.ByteString; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.UnsafeByteOperations; import io.netty.bootstrap.Bootstrap; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoopGroup; import io.netty.channel.WriteBufferWaterMark; import io.netty.channel.epoll.EpollChannelOption; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.unix.Errors.NativeIoException; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.DecoderException; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.TooLongFrameException; import io.netty.handler.flush.FlushConsolidationHandler; import io.netty.handler.ssl.SslHandler; import io.netty.incubator.channel.uring.IOUringChannelOption; import io.netty.incubator.channel.uring.IOUringEventLoopGroup; import io.netty.incubator.channel.uring.IOUringSocketChannel; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.UnknownHostException; import java.security.cert.Certificate; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.Queue; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.BiPredicate; import javax.net.ssl.SSLException; import javax.net.ssl.SSLPeerUnverifiedException; import lombok.SneakyThrows; import org.apache.bookkeeper.auth.BookKeeperPrincipal; import org.apache.bookkeeper.auth.ClientAuthProvider; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookKeeperClientStats; import org.apache.bookkeeper.client.BookieInfoReader.BookieInfo; import org.apache.bookkeeper.client.api.WriteFlag; import org.apache.bookkeeper.common.util.MdcUtils; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ForceLedgerCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GetBookieInfoCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GetListOfEntriesOfLedgerCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallbackCtx; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadLacCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.StartTLSCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteLacCallback; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.BKPacketHeader; import org.apache.bookkeeper.proto.BookkeeperProtocol.ForceLedgerRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ForceLedgerResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetBookieInfoRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetBookieInfoResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetListOfEntriesOfLedgerRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetListOfEntriesOfLedgerResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.OperationType; import org.apache.bookkeeper.proto.BookkeeperProtocol.ProtocolVersion; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadLacRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadLacResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.proto.BookkeeperProtocol.WriteLacRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.WriteLacResponse; 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.tls.SecurityException; import org.apache.bookkeeper.tls.SecurityHandlerFactory; import org.apache.bookkeeper.tls.SecurityHandlerFactory.NodeType; import org.apache.bookkeeper.util.AvailabilityOfEntriesOfLedger; import org.apache.bookkeeper.util.ByteBufList; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.util.StringUtils; import org.apache.bookkeeper.util.collections.ConcurrentOpenHashMap; import org.apache.bookkeeper.util.collections.SynchronizedHashMultiMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * This class manages all details of connection to a particular bookie. It also * has reconnect logic if a connection to a bookie fails. */ @StatsDoc( name = BookKeeperClientStats.CHANNEL_SCOPE, help = "Per channel bookie client stats" ) @Sharable public class PerChannelBookieClient extends ChannelInboundHandlerAdapter { static final Logger LOG = LoggerFactory.getLogger(PerChannelBookieClient.class); // this set contains the bookie error return codes that we do not consider for a bookie to be "faulty" private static final Set<Integer> expectedBkOperationErrors = Collections.unmodifiableSet(Sets .newHashSet(BKException.Code.BookieHandleNotAvailableException, BKException.Code.NoSuchEntryException, BKException.Code.NoSuchLedgerExistsException, BKException.Code.LedgerFencedException, BKException.Code.LedgerExistException, BKException.Code.DuplicateEntryIdException, BKException.Code.WriteOnReadOnlyBookieException)); private static final int DEFAULT_HIGH_PRIORITY_VALUE = 100; // We may add finer grained priority later. private static final AtomicLong txnIdGenerator = new AtomicLong(0); final BookieId bookieId; final BookieAddressResolver bookieAddressResolver; final EventLoopGroup eventLoopGroup; final ByteBufAllocator allocator; final OrderedExecutor executor; final long addEntryTimeoutNanos; final long readEntryTimeoutNanos; final int maxFrameSize; final long getBookieInfoTimeoutNanos; final int startTLSTimeout; private final ConcurrentOpenHashMap<CompletionKey, CompletionValue> completionObjects = ConcurrentOpenHashMap.<CompletionKey, CompletionValue>newBuilder().autoShrink(true).build(); // Map that hold duplicated read requests. The idea is to only use this map (synchronized) when there is a duplicate // read request for the same ledgerId/entryId private final SynchronizedHashMultiMap<CompletionKey, CompletionValue> completionObjectsV2Conflicts = new SynchronizedHashMultiMap<>(); private final StatsLogger statsLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_READ_OP, help = "channel stats of read entries requests" ) private final OpStatsLogger readEntryOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_READ, help = "timeout stats of read entries requests" ) private final OpStatsLogger readTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_ADD_OP, help = "channel stats of add entries requests" ) private final OpStatsLogger addEntryOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_WRITE_LAC_OP, help = "channel stats of write_lac requests" ) private final OpStatsLogger writeLacOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_FORCE_OP, help = "channel stats of force requests" ) private final OpStatsLogger forceLedgerOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_READ_LAC_OP, help = "channel stats of read_lac requests" ) private final OpStatsLogger readLacOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_ADD, help = "timeout stats of add entries requests" ) private final OpStatsLogger addTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_WRITE_LAC, help = "timeout stats of write_lac requests" ) private final OpStatsLogger writeLacTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_FORCE, help = "timeout stats of force requests" ) private final OpStatsLogger forceLedgerTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_READ_LAC, help = "timeout stats of read_lac requests" ) private final OpStatsLogger readLacTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.GET_BOOKIE_INFO_OP, help = "channel stats of get_bookie_info requests" ) private final OpStatsLogger getBookieInfoOpLogger; @StatsDoc( name = BookKeeperClientStats.TIMEOUT_GET_BOOKIE_INFO, help = "timeout stats of get_bookie_info requests" ) private final OpStatsLogger getBookieInfoTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_START_TLS_OP, help = "channel stats of start_tls requests" ) private final OpStatsLogger startTLSOpLogger; @StatsDoc( name = BookKeeperClientStats.CHANNEL_TIMEOUT_START_TLS_OP, help = "timeout stats of start_tls requests" ) private final OpStatsLogger startTLSTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.CLIENT_CONNECT_TIMER, help = "channel stats of connect requests" ) private final OpStatsLogger connectTimer; private final OpStatsLogger getListOfEntriesOfLedgerCompletionOpLogger; private final OpStatsLogger getListOfEntriesOfLedgerCompletionTimeoutOpLogger; @StatsDoc( name = BookKeeperClientStats.NETTY_EXCEPTION_CNT, help = "the number of exceptions received from this channel" ) private final Counter exceptionCounter; @StatsDoc( name = BookKeeperClientStats.ADD_OP_OUTSTANDING, help = "the number of outstanding add_entry requests" ) private final Counter addEntryOutstanding; @StatsDoc( name = BookKeeperClientStats.READ_OP_OUTSTANDING, help = "the number of outstanding add_entry requests" ) private final Counter readEntryOutstanding; /* collect stats on all Ops that flows through netty pipeline */ @StatsDoc( name = BookKeeperClientStats.NETTY_OPS, help = "channel stats for all operations flowing through netty pipeline" ) private final OpStatsLogger nettyOpLogger; @StatsDoc( name = BookKeeperClientStats.ACTIVE_NON_TLS_CHANNEL_COUNTER, help = "the number of active non-tls channels" ) private final Counter activeNonTlsChannelCounter; @StatsDoc( name = BookKeeperClientStats.ACTIVE_TLS_CHANNEL_COUNTER, help = "the number of active tls channels" ) private final Counter activeTlsChannelCounter; @StatsDoc( name = BookKeeperClientStats.FAILED_CONNECTION_COUNTER, help = "the number of failed connections" ) private final Counter failedConnectionCounter; @StatsDoc( name = BookKeeperClientStats.FAILED_TLS_HANDSHAKE_COUNTER, help = "the number of failed tls handshakes" ) private final Counter failedTlsHandshakeCounter; private final boolean useV2WireProtocol; private final boolean preserveMdcForTaskExecution; /** * The following member variables do not need to be concurrent, or volatile * because they are always updated under a lock. */ private volatile Queue<GenericCallback<PerChannelBookieClient>> pendingOps = new ArrayDeque<GenericCallback<PerChannelBookieClient>>(); volatile Channel channel = null; private final ClientConnectionPeer connectionPeer; private volatile BookKeeperPrincipal authorizedId = BookKeeperPrincipal.ANONYMOUS; @SneakyThrows private FailedChannelFutureImpl processBookieNotResolvedError(long startTime, BookieAddressResolver.BookieIdNotResolvedException err) { FailedChannelFutureImpl failedFuture = new FailedChannelFutureImpl(err); contextPreservingListener(new ConnectionFutureListener(startTime)).operationComplete(failedFuture); return failedFuture; } enum ConnectionState { DISCONNECTED, CONNECTING, CONNECTED, CLOSED, START_TLS } volatile ConnectionState state; final ReentrantReadWriteLock closeLock = new ReentrantReadWriteLock(); private final ClientConfiguration conf; private final PerChannelBookieClientPool pcbcPool; private final ClientAuthProvider.Factory authProviderFactory; private final ExtensionRegistry extRegistry; private final SecurityHandlerFactory shFactory; private volatile boolean isWritable = true; private long lastBookieUnavailableLogTimestamp = 0; public PerChannelBookieClient(OrderedExecutor executor, EventLoopGroup eventLoopGroup, BookieId addr, BookieAddressResolver bookieAddressResolver) throws SecurityException { this(new ClientConfiguration(), executor, eventLoopGroup, addr, NullStatsLogger.INSTANCE, null, null, null, bookieAddressResolver); } public PerChannelBookieClient(OrderedExecutor executor, EventLoopGroup eventLoopGroup, BookieId bookieId, ClientAuthProvider.Factory authProviderFactory, ExtensionRegistry extRegistry, BookieAddressResolver bookieAddressResolver) throws SecurityException { this(new ClientConfiguration(), executor, eventLoopGroup, bookieId, NullStatsLogger.INSTANCE, authProviderFactory, extRegistry, null, bookieAddressResolver); } public PerChannelBookieClient(ClientConfiguration conf, OrderedExecutor executor, EventLoopGroup eventLoopGroup, BookieId bookieId, StatsLogger parentStatsLogger, ClientAuthProvider.Factory authProviderFactory, ExtensionRegistry extRegistry, PerChannelBookieClientPool pcbcPool, BookieAddressResolver bookieAddressResolver) throws SecurityException { this(conf, executor, eventLoopGroup, UnpooledByteBufAllocator.DEFAULT, bookieId, NullStatsLogger.INSTANCE, authProviderFactory, extRegistry, pcbcPool, null, bookieAddressResolver); } public PerChannelBookieClient(ClientConfiguration conf, OrderedExecutor executor, EventLoopGroup eventLoopGroup, ByteBufAllocator allocator, BookieId bookieId, StatsLogger parentStatsLogger, ClientAuthProvider.Factory authProviderFactory, ExtensionRegistry extRegistry, PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory, BookieAddressResolver bookieAddressResolver) throws SecurityException { this.maxFrameSize = conf.getNettyMaxFrameSizeBytes(); this.conf = conf; this.bookieId = bookieId; this.bookieAddressResolver = bookieAddressResolver; this.executor = executor; if (LocalBookiesRegistry.isLocalBookie(bookieId)) { this.eventLoopGroup = new DefaultEventLoopGroup(); } else { this.eventLoopGroup = eventLoopGroup; } this.allocator = allocator; this.state = ConnectionState.DISCONNECTED; this.addEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getAddEntryTimeout()); this.readEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getReadEntryTimeout()); this.getBookieInfoTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getBookieInfoTimeout()); this.startTLSTimeout = conf.getStartTLSTimeout(); this.useV2WireProtocol = conf.getUseV2WireProtocol(); this.preserveMdcForTaskExecution = conf.getPreserveMdcForTaskExecution(); this.authProviderFactory = authProviderFactory; this.extRegistry = extRegistry; this.shFactory = shFactory; if (shFactory != null) { shFactory.init(NodeType.Client, conf, allocator); } this.statsLogger = parentStatsLogger.scope(BookKeeperClientStats.CHANNEL_SCOPE) .scopeLabel(BookKeeperClientStats.BOOKIE_LABEL, bookieId.toString()); readEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_OP); addEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_ADD_OP); writeLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_WRITE_LAC_OP); forceLedgerOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_FORCE_OP); readLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_LAC_OP); getBookieInfoOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.GET_BOOKIE_INFO_OP); getListOfEntriesOfLedgerCompletionOpLogger = statsLogger .getOpStatsLogger(BookKeeperClientStats.GET_LIST_OF_ENTRIES_OF_LEDGER_OP); readTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ); addTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_ADD); writeLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_WRITE_LAC); forceLedgerTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_FORCE); readLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ_LAC); getBookieInfoTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_BOOKIE_INFO); startTLSOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_START_TLS_OP); startTLSTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_START_TLS_OP); getListOfEntriesOfLedgerCompletionTimeoutOpLogger = statsLogger .getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_LIST_OF_ENTRIES_OF_LEDGER); exceptionCounter = statsLogger.getCounter(BookKeeperClientStats.NETTY_EXCEPTION_CNT); connectTimer = statsLogger.getOpStatsLogger(BookKeeperClientStats.CLIENT_CONNECT_TIMER); addEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.ADD_OP_OUTSTANDING); readEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.READ_OP_OUTSTANDING); nettyOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.NETTY_OPS); activeNonTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_NON_TLS_CHANNEL_COUNTER); activeTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_TLS_CHANNEL_COUNTER); failedConnectionCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_CONNECTION_COUNTER); failedTlsHandshakeCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_TLS_HANDSHAKE_COUNTER); this.pcbcPool = pcbcPool; this.connectionPeer = new ClientConnectionPeer() { @Override public SocketAddress getRemoteAddr() { Channel c = channel; if (c != null) { return c.remoteAddress(); } else { return null; } } @Override public Collection<Object> getProtocolPrincipals() { Channel c = channel; if (c == null) { return Collections.emptyList(); } SslHandler ssl = c.pipeline().get(SslHandler.class); if (ssl == null) { return Collections.emptyList(); } try { Certificate[] certificates = ssl.engine().getSession().getPeerCertificates(); if (certificates == null) { return Collections.emptyList(); } List<Object> result = new ArrayList<>(); result.addAll(Arrays.asList(certificates)); return result; } catch (SSLPeerUnverifiedException err) { return Collections.emptyList(); } } @Override public void disconnect() { Channel c = channel; if (c != null) { c.close().addListener(x -> makeWritable()); } LOG.info("authplugin disconnected channel {}", channel); } @Override public void setAuthorizedId(BookKeeperPrincipal principal) { authorizedId = principal; LOG.info("connection {} authenticated as {}", channel, principal); } @Override public BookKeeperPrincipal getAuthorizedId() { return authorizedId; } @Override public boolean isSecure() { Channel c = channel; if (c == null) { return false; } else { return c.pipeline().get(SslHandler.class) != null; } } }; } private void completeOperation(GenericCallback<PerChannelBookieClient> op, int rc) { closeLock.readLock().lock(); try { if (ConnectionState.CLOSED == state) { op.operationComplete(BKException.Code.ClientClosedException, this); } else { op.operationComplete(rc, this); } } finally { closeLock.readLock().unlock(); } } protected long getNumPendingCompletionRequests() { return completionObjects.size(); } protected ChannelFuture connect() { final long startTime = MathUtils.nowInNano(); if (LOG.isDebugEnabled()) { LOG.debug("Connecting to bookie: {}", bookieId); } BookieSocketAddress addr; try { addr = bookieAddressResolver.resolve(bookieId); } catch (BookieAddressResolver.BookieIdNotResolvedException err) { LOG.error("Cannot connect to {} as endpoint resolution failed (probably bookie is down) err {}", bookieId, err.toString()); return processBookieNotResolvedError(startTime, err); } // Set up the ClientBootStrap so we can create a new Channel connection to the bookie. Bootstrap bootstrap = new Bootstrap(); bootstrap.group(eventLoopGroup); if (eventLoopGroup instanceof IOUringEventLoopGroup) { bootstrap.channel(IOUringSocketChannel.class); try { bootstrap.option(IOUringChannelOption.TCP_USER_TIMEOUT, conf.getTcpUserTimeoutMillis()); } catch (NoSuchElementException e) { // Property not set, so keeping default value. } } else if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollSocketChannel.class); try { // For Epoll channels, configure the TCP user timeout. bootstrap.option(EpollChannelOption.TCP_USER_TIMEOUT, conf.getTcpUserTimeoutMillis()); } catch (NoSuchElementException e) { // Property not set, so keeping default value. } } else if (eventLoopGroup instanceof DefaultEventLoopGroup) { bootstrap.channel(LocalChannel.class); } else { bootstrap.channel(NioSocketChannel.class); } bootstrap.option(ChannelOption.ALLOCATOR, this.allocator); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, conf.getClientConnectTimeoutMillis()); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getClientWriteBufferLowWaterMark(), conf.getClientWriteBufferHighWaterMark())); if (!(eventLoopGroup instanceof DefaultEventLoopGroup)) { bootstrap.option(ChannelOption.TCP_NODELAY, conf.getClientTcpNoDelay()); bootstrap.option(ChannelOption.SO_KEEPALIVE, conf.getClientSockKeepalive()); // if buffer sizes are 0, let OS auto-tune it if (conf.getClientSendBufferSize() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, conf.getClientSendBufferSize()); } if (conf.getClientReceiveBufferSize() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, conf.getClientReceiveBufferSize()); } } // In the netty pipeline, we need to split packets based on length, so we // use the {@link LengthFieldBasedFramDecoder}. Other than that all actions // are carried out in this class, e.g., making sense of received messages, // prepending the length to outgoing packets etc. bootstrap.handler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("consolidation", new FlushConsolidationHandler(1024, true)); pipeline.addLast("bytebufList", ByteBufList.ENCODER); pipeline.addLast("lengthbasedframedecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.RequestEncoder(extRegistry)); pipeline.addLast( "bookieProtoDecoder", new BookieProtoEncoding.ResponseDecoder(extRegistry, useV2WireProtocol, shFactory != null)); pipeline.addLast("authHandler", new AuthHandler.ClientSideHandler(authProviderFactory, txnIdGenerator, connectionPeer, useV2WireProtocol)); pipeline.addLast("mainhandler", PerChannelBookieClient.this); } }); SocketAddress bookieAddr = addr.getSocketAddress(); if (eventLoopGroup instanceof DefaultEventLoopGroup) { bookieAddr = new LocalAddress(bookieId.toString()); } ChannelFuture future = bootstrap.connect(bookieAddr); future.addListener(contextPreservingListener(new ConnectionFutureListener(startTime))); future.addListener(x -> makeWritable()); return future; } void cleanDisconnectAndClose() { disconnect(); close(); } /** * * @return boolean, true is PCBC is writable */ public boolean isWritable() { return isWritable; } public void setWritable(boolean val) { isWritable = val; } private void makeWritable() { setWritable(true); } void connectIfNeededAndDoOp(GenericCallback<PerChannelBookieClient> op) { boolean completeOpNow = false; int opRc = BKException.Code.OK; // common case without lock first if (channel != null && state == ConnectionState.CONNECTED) { completeOpNow = true; } else { synchronized (this) { // check the channel status again under lock if (channel != null && state == ConnectionState.CONNECTED) { completeOpNow = true; opRc = BKException.Code.OK; } else if (state == ConnectionState.CLOSED) { completeOpNow = true; opRc = BKException.Code.BookieHandleNotAvailableException; } else { // channel is either null (first connection attempt), or the // channel is disconnected. Connection attempt is still in // progress, queue up this op. Op will be executed when // connection attempt either fails or succeeds pendingOps.add(op); if (state == ConnectionState.CONNECTING || state == ConnectionState.START_TLS) { // the connection request has already been sent and it is waiting for the response. return; } // switch state to connecting and do connection attempt state = ConnectionState.CONNECTING; } } if (!completeOpNow) { // Start connection attempt to the input server host. connect(); } } if (completeOpNow) { completeOperation(op, opRc); } } void writeLac(final long ledgerId, final byte[] masterKey, final long lac, ByteBufList toSend, WriteLacCallback cb, Object ctx) { final long txnId = getTxnId(); final CompletionKey completionKey = new V3CompletionKey(txnId, OperationType.WRITE_LAC); // writeLac is mostly like addEntry hence uses addEntryTimeout completionObjects.put(completionKey, new WriteLacCompletion(completionKey, cb, ctx, ledgerId)); // Build the request BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.WRITE_LAC) .setTxnId(txnId); ByteString body; if (toSend.hasArray()) { body = UnsafeByteOperations.unsafeWrap(toSend.array(), toSend.arrayOffset(), toSend.readableBytes()); } else if (toSend.size() == 1) { body = UnsafeByteOperations.unsafeWrap(toSend.getBuffer(0).nioBuffer()); } else { body = UnsafeByteOperations.unsafeWrap(toSend.toArray()); } WriteLacRequest.Builder writeLacBuilder = WriteLacRequest.newBuilder() .setLedgerId(ledgerId) .setLac(lac) .setMasterKey(UnsafeByteOperations.unsafeWrap(masterKey)) .setBody(body); final Request writeLacRequest = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setWriteLacRequest(writeLacBuilder) .build(); writeAndFlush(channel, completionKey, writeLacRequest); } void forceLedger(final long ledgerId, ForceLedgerCallback cb, Object ctx) { if (useV2WireProtocol) { LOG.error("force is not allowed with v2 protocol"); executor.executeOrdered(ledgerId, () -> { cb.forceLedgerComplete(BKException.Code.IllegalOpException, ledgerId, bookieId, ctx); }); return; } final long txnId = getTxnId(); final CompletionKey completionKey = new V3CompletionKey(txnId, OperationType.FORCE_LEDGER); // force is mostly like addEntry hence uses addEntryTimeout completionObjects.put(completionKey, new ForceLedgerCompletion(completionKey, cb, ctx, ledgerId)); // Build the request BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.FORCE_LEDGER) .setTxnId(txnId); ForceLedgerRequest.Builder writeLacBuilder = ForceLedgerRequest.newBuilder() .setLedgerId(ledgerId); final Request forceLedgerRequest = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setForceLedgerRequest(writeLacBuilder) .build(); writeAndFlush(channel, completionKey, forceLedgerRequest); } /** * This method should be called only after connection has been checked for * {@link #connectIfNeededAndDoOp(GenericCallback)}. * * @param ledgerId * Ledger Id * @param masterKey * Master Key * @param entryId * Entry Id * @param toSend * Buffer to send * @param cb * Write callback * @param ctx * Write callback context * @param allowFastFail * allowFastFail flag * @param writeFlags * WriteFlags */ void addEntry(final long ledgerId, byte[] masterKey, final long entryId, ReferenceCounted toSend, WriteCallback cb, Object ctx, final int options, boolean allowFastFail, final EnumSet<WriteFlag> writeFlags) { Object request = null; CompletionKey completionKey = null; if (useV2WireProtocol) { if (writeFlags.contains(WriteFlag.DEFERRED_SYNC)) { LOG.error("invalid writeflags {} for v2 protocol", writeFlags); cb.writeComplete(BKException.Code.IllegalOpException, ledgerId, entryId, bookieId, ctx); return; } completionKey = acquireV2Key(ledgerId, entryId, OperationType.ADD_ENTRY); if (toSend instanceof ByteBuf) { request = ((ByteBuf) toSend).retainedDuplicate(); } else { request = ByteBufList.clone((ByteBufList) toSend); } } else { final long txnId = getTxnId(); completionKey = new V3CompletionKey(txnId, OperationType.ADD_ENTRY); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.ADD_ENTRY) .setTxnId(txnId); if (((short) options & BookieProtocol.FLAG_HIGH_PRIORITY) == BookieProtocol.FLAG_HIGH_PRIORITY) { headerBuilder.setPriority(DEFAULT_HIGH_PRIORITY_VALUE); } ByteString body = null; ByteBufList bufToSend = (ByteBufList) toSend; if (bufToSend.hasArray()) { body = UnsafeByteOperations.unsafeWrap(bufToSend.array(), bufToSend.arrayOffset(), bufToSend.readableBytes()); } else { for (int i = 0; i < bufToSend.size(); i++) { ByteString piece = UnsafeByteOperations.unsafeWrap(bufToSend.getBuffer(i).nioBuffer()); // use ByteString.concat to avoid byte[] allocation when toSend has multiple ByteBufs body = (body == null) ? piece : body.concat(piece); } } AddRequest.Builder addBuilder = AddRequest.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId) .setMasterKey(UnsafeByteOperations.unsafeWrap(masterKey)) .setBody(body); if (((short) options & BookieProtocol.FLAG_RECOVERY_ADD) == BookieProtocol.FLAG_RECOVERY_ADD) { addBuilder.setFlag(AddRequest.Flag.RECOVERY_ADD); } if (!writeFlags.isEmpty()) { // add flags only if needed, in order to be able to talk with old bookies addBuilder.setWriteFlags(WriteFlag.getWriteFlagsValue(writeFlags)); } request = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setAddRequest(addBuilder) .build(); } putCompletionKeyValue(completionKey, acquireAddCompletion(completionKey, cb, ctx, ledgerId, entryId)); final Channel c = channel; if (c == null) { // usually checked in writeAndFlush, but we have extra check // because we need to release toSend. errorOut(completionKey); ReferenceCountUtil.release(toSend); return; } else { // addEntry times out on backpressure writeAndFlush(c, completionKey, request, allowFastFail); } } public void readLac(final long ledgerId, ReadLacCallback cb, Object ctx) { Object request = null; CompletionKey completionKey = null; if (useV2WireProtocol) { request = BookieProtocol.ReadRequest.create(BookieProtocol.CURRENT_PROTOCOL_VERSION, ledgerId, 0, (short) 0, null); completionKey = acquireV2Key(ledgerId, 0, OperationType.READ_LAC); } else { final long txnId = getTxnId(); completionKey = new V3CompletionKey(txnId, OperationType.READ_LAC); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.READ_LAC) .setTxnId(txnId); ReadLacRequest.Builder readLacBuilder = ReadLacRequest.newBuilder() .setLedgerId(ledgerId); request = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setReadLacRequest(readLacBuilder) .build(); } putCompletionKeyValue(completionKey, new ReadLacCompletion(completionKey, cb, ctx, ledgerId)); writeAndFlush(channel, completionKey, request); } public void getListOfEntriesOfLedger(final long ledgerId, GetListOfEntriesOfLedgerCallback cb) { final long txnId = getTxnId(); final CompletionKey completionKey = new V3CompletionKey(txnId, OperationType.GET_LIST_OF_ENTRIES_OF_LEDGER); completionObjects.put(completionKey, new GetListOfEntriesOfLedgerCompletion(completionKey, cb, ledgerId)); // Build the request. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder().setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.GET_LIST_OF_ENTRIES_OF_LEDGER).setTxnId(txnId); GetListOfEntriesOfLedgerRequest.Builder getListOfEntriesOfLedgerRequestBuilder = GetListOfEntriesOfLedgerRequest.newBuilder().setLedgerId(ledgerId); final Request getListOfEntriesOfLedgerRequest = Request.newBuilder().setHeader(headerBuilder) .setGetListOfEntriesOfLedgerRequest(getListOfEntriesOfLedgerRequestBuilder).build(); writeAndFlush(channel, completionKey, getListOfEntriesOfLedgerRequest); } /** * Long Poll Reads. */ public void readEntryWaitForLACUpdate(final long ledgerId, final long entryId, final long previousLAC, final long timeOutInMillis, final boolean piggyBackEntry, ReadEntryCallback cb, Object ctx) { readEntryInternal(ledgerId, entryId, previousLAC, timeOutInMillis, piggyBackEntry, cb, ctx, (short) 0, null, false); } /** * Normal Reads. */ public void readEntry(final long ledgerId, final long entryId, ReadEntryCallback cb, Object ctx, int flags, byte[] masterKey, boolean allowFastFail) { readEntryInternal(ledgerId, entryId, null, null, false, cb, ctx, (short) flags, masterKey, allowFastFail); } private void readEntryInternal(final long ledgerId, final long entryId, final Long previousLAC, final Long timeOutInMillis, final boolean piggyBackEntry, final ReadEntryCallback cb, final Object ctx, int flags, byte[] masterKey, boolean allowFastFail) { Object request = null; CompletionKey completionKey = null; if (useV2WireProtocol) { request = BookieProtocol.ReadRequest.create(BookieProtocol.CURRENT_PROTOCOL_VERSION, ledgerId, entryId, (short) flags, masterKey); completionKey = acquireV2Key(ledgerId, entryId, OperationType.READ_ENTRY); } else { final long txnId = getTxnId(); completionKey = new V3CompletionKey(txnId, OperationType.READ_ENTRY); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.READ_ENTRY) .setTxnId(txnId); if (((short) flags & BookieProtocol.FLAG_HIGH_PRIORITY) == BookieProtocol.FLAG_HIGH_PRIORITY) { headerBuilder.setPriority(DEFAULT_HIGH_PRIORITY_VALUE); } ReadRequest.Builder readBuilder = ReadRequest.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); if (null != previousLAC) { readBuilder = readBuilder.setPreviousLAC(previousLAC); } if (null != timeOutInMillis) { // Long poll requires previousLAC if (null == previousLAC) { cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx); return; } readBuilder = readBuilder.setTimeOut(timeOutInMillis); } if (piggyBackEntry) { // Long poll requires previousLAC if (null == previousLAC) { cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx); return; } readBuilder = readBuilder.setFlag(ReadRequest.Flag.ENTRY_PIGGYBACK); } // Only one flag can be set on the read requests if (((short) flags & BookieProtocol.FLAG_DO_FENCING) == BookieProtocol.FLAG_DO_FENCING) { readBuilder.setFlag(ReadRequest.Flag.FENCE_LEDGER); if (masterKey == null) { cb.readEntryComplete(BKException.Code.IncorrectParameterException, ledgerId, entryId, null, ctx); return; } readBuilder.setMasterKey(ByteString.copyFrom(masterKey)); } request = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setReadRequest(readBuilder) .build(); } ReadCompletion readCompletion = new ReadCompletion(completionKey, cb, ctx, ledgerId, entryId); putCompletionKeyValue(completionKey, readCompletion); writeAndFlush(channel, completionKey, request, allowFastFail); } public void getBookieInfo(final long requested, GetBookieInfoCallback cb, Object ctx) { final long txnId = getTxnId(); final CompletionKey completionKey = new V3CompletionKey(txnId, OperationType.GET_BOOKIE_INFO); completionObjects.put(completionKey, new GetBookieInfoCompletion( completionKey, cb, ctx)); // Build the request and calculate the total size to be included in the packet. BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.GET_BOOKIE_INFO) .setTxnId(txnId); GetBookieInfoRequest.Builder getBookieInfoBuilder = GetBookieInfoRequest.newBuilder() .setRequested(requested); final Request getBookieInfoRequest = withRequestContext(Request.newBuilder()) .setHeader(headerBuilder) .setGetBookieInfoRequest(getBookieInfoBuilder) .build(); writeAndFlush(channel, completionKey, getBookieInfoRequest); } private static final BiPredicate<CompletionKey, CompletionValue> timeoutCheck = (key, value) -> { return value.maybeTimeout(); }; public void checkTimeoutOnPendingOperations() { int timedOutOperations = completionObjects.removeIf(timeoutCheck); timedOutOperations += completionObjectsV2Conflicts.removeIf(timeoutCheck); if (timedOutOperations > 0) { LOG.info("Timed-out {} operations to channel {} for {}", timedOutOperations, channel, bookieId); } } /** * Disconnects the bookie client. It can be reused. */ public void disconnect() { disconnect(true); } public void disconnect(boolean wait) { LOG.info("Disconnecting the per channel bookie client for {}", bookieId); closeInternal(false, wait); } /** * Closes the bookie client permanently. It cannot be reused. */ public void close() { close(true); } public void close(boolean wait) { LOG.info("Closing the per channel bookie client for {}", bookieId); closeLock.writeLock().lock(); try { if (ConnectionState.CLOSED == state) { return; } state = ConnectionState.CLOSED; errorOutOutstandingEntries(BKException.Code.ClientClosedException); } finally { closeLock.writeLock().unlock(); } if (channel != null && channel.pipeline().get(SslHandler.class) != null) { activeTlsChannelCounter.dec(); } else { activeNonTlsChannelCounter.dec(); } closeInternal(true, wait); } private void closeInternal(boolean permanent, boolean wait) { Channel toClose = null; synchronized (this) { if (permanent) { state = ConnectionState.CLOSED; } else if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } toClose = channel; channel = null; makeWritable(); } if (toClose != null) { ChannelFuture cf = closeChannel(toClose); if (wait) { cf.awaitUninterruptibly(); } } } private ChannelFuture closeChannel(Channel c) { if (LOG.isDebugEnabled()) { LOG.debug("Closing channel {}", c); } return c.close().addListener(x -> makeWritable()); } @Override public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { final Channel c = channel; if (c == null || c.isWritable()) { makeWritable(); } super.channelWritabilityChanged(ctx); } private void writeAndFlush(final Channel channel, final CompletionKey key, final Object request) { writeAndFlush(channel, key, request, false); } private void writeAndFlush(final Channel channel, final CompletionKey key, final Object request, final boolean allowFastFail) { if (channel == null) { LOG.warn("Operation {} failed: channel == null", StringUtils.requestToString(request)); errorOut(key); return; } final boolean isChannelWritable = channel.isWritable(); if (isWritable != isChannelWritable) { // isWritable is volatile so simple "isWritable = channel.isWritable()" would be slower isWritable = isChannelWritable; } if (allowFastFail && !isWritable) { LOG.warn("Operation {} failed: TooManyRequestsException", StringUtils.requestToString(request)); errorOut(key, BKException.Code.TooManyRequestsException); return; } try { final long startTime = MathUtils.nowInNano(); ChannelPromise promise = channel.newPromise().addListener(future -> { if (future.isSuccess()) { nettyOpLogger.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); CompletionValue completion = completionObjects.get(key); if (completion != null) { completion.setOutstanding(); } } else { nettyOpLogger.registerFailedEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } }); channel.writeAndFlush(request, promise); } catch (Throwable e) { LOG.warn("Operation {} failed", StringUtils.requestToString(request), e); errorOut(key); } } void errorOut(final CompletionKey key) { if (LOG.isDebugEnabled()) { LOG.debug("Removing completion key: {}", key); } CompletionValue completion = completionObjects.remove(key); if (completion != null) { completion.errorOut(); } else { // If there's no completion object here, try in the multimap completionObjectsV2Conflicts.removeAny(key).ifPresent(c -> c.errorOut()); } } void errorOut(final CompletionKey key, final int rc) { if (LOG.isDebugEnabled()) { LOG.debug("Removing completion key: {}", key); } CompletionValue completion = completionObjects.remove(key); if (completion != null) { completion.errorOut(rc); } else { // If there's no completion object here, try in the multimap completionObjectsV2Conflicts.removeAny(key).ifPresent(c -> c.errorOut(rc)); } } /** * Errors out pending ops from per channel bookie client. As the channel * is being closed, all the operations waiting on the connection * will be sent to completion with error. */ void errorOutPendingOps(int rc) { Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps; synchronized (this) { oldPendingOps = pendingOps; pendingOps = new ArrayDeque<>(); } for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, PerChannelBookieClient.this); } } /** * Errors out pending entries. We call this method from one thread to avoid * concurrent executions to QuorumOpMonitor (implements callbacks). It seems * simpler to call it from BookieHandle instead of calling directly from * here. */ void errorOutOutstandingEntries(int rc) { Optional<CompletionKey> multikey = completionObjectsV2Conflicts.getAnyKey(); while (multikey.isPresent()) { multikey.ifPresent(k -> errorOut(k, rc)); multikey = completionObjectsV2Conflicts.getAnyKey(); } for (CompletionKey key : completionObjects.keys()) { errorOut(key, rc); } } void recordError() { if (pcbcPool != null) { pcbcPool.recordError(); } } /** * If our channel has disconnected, we just error out the pending entries. */ @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { LOG.info("Disconnected from bookie channel {}", ctx.channel()); if (ctx.channel() != null) { closeChannel(ctx.channel()); if (ctx.channel().pipeline().get(SslHandler.class) != null) { activeTlsChannelCounter.dec(); } else { activeNonTlsChannelCounter.dec(); } } errorOutOutstandingEntries(BKException.Code.BookieHandleNotAvailableException); errorOutPendingOps(BKException.Code.BookieHandleNotAvailableException); synchronized (this) { if (this.channel == ctx.channel() && state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; channel = null; } } // we don't want to reconnect right away. If someone sends a request to // this address, we will reconnect. } /** * Called by netty when an exception happens in one of the netty threads * (mostly due to what we do in the netty threads). */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { exceptionCounter.inc(); if (cause instanceof CorruptedFrameException || cause instanceof TooLongFrameException) { LOG.error("Corrupted frame received from bookie: {}", ctx.channel()); ctx.close(); return; } if (cause instanceof AuthHandler.AuthenticationException) { LOG.error("Error authenticating connection", cause); errorOutOutstandingEntries(BKException.Code.UnauthorizedAccessException); Channel c = ctx.channel(); if (c != null) { closeChannel(c); } return; } // TLSv1.3 doesn't throw SSLHandshakeException for certificate issues // see https://stackoverflow.com/a/62465859 for details about the reason // therefore catch SSLException to also cover TLSv1.3 if (cause instanceof DecoderException && cause.getCause() instanceof SSLException) { LOG.error("TLS handshake failed", cause); errorOutPendingOps(BKException.Code.SecurityException); Channel c = ctx.channel(); if (c != null) { closeChannel(c); } return; } if (cause instanceof IOException) { if (cause instanceof NativeIoException) { // Stack trace is not very interesting for native IO exceptio, the important part is in // the exception message LOG.warn("Exception caught on:{} cause: {}", ctx.channel(), cause.getMessage()); } else { LOG.warn("Exception caught on:{} cause:", ctx.channel(), cause); } ctx.close(); return; } synchronized (this) { if (state == ConnectionState.CLOSED) { if (LOG.isDebugEnabled()) { LOG.debug("Unexpected exception caught by bookie client channel handler, " + "but the client is closed, so it isn't important", cause); } } else { LOG.error("Unexpected exception caught by bookie client channel handler", cause); } } // Since we are a library, cant terminate App here, can we? ctx.close(); } /** * Called by netty when a message is received on a channel. */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (msg instanceof BookieProtocol.Response) { BookieProtocol.Response response = (BookieProtocol.Response) msg; readV2Response(response); } else if (msg instanceof Response) { Response response = (Response) msg; readV3Response(response); } else { ctx.fireChannelRead(msg); } } private void readV2Response(final BookieProtocol.Response response) { OperationType operationType = getOperationType(response.getOpCode()); StatusCode status = getStatusCodeFromErrorCode(response.errorCode); CompletionKey key = acquireV2Key(response.ledgerId, response.entryId, operationType); CompletionValue completionValue = getCompletionValue(key); key.release(); if (null == completionValue) { // Unexpected response, so log it. The txnId should have been present. if (LOG.isDebugEnabled()) { LOG.debug("Unexpected response received from bookie : " + bookieId + " for type : " + operationType + " and ledger:entry : " + response.ledgerId + ":" + response.entryId); } response.release(); } else { long orderingKey = completionValue.ledgerId; executor.executeOrdered(orderingKey, ReadV2ResponseCallback.create(completionValue, response.ledgerId, response.entryId, status, response)); } } private static class ReadV2ResponseCallback implements Runnable { CompletionValue completionValue; long ledgerId; long entryId; StatusCode status; BookieProtocol.Response response; static ReadV2ResponseCallback create(CompletionValue completionValue, long ledgerId, long entryId, StatusCode status, BookieProtocol.Response response) { ReadV2ResponseCallback callback = RECYCLER.get(); callback.completionValue = completionValue; callback.ledgerId = ledgerId; callback.entryId = entryId; callback.status = status; callback.response = response; return callback; } @Override public void run() { completionValue.handleV2Response(ledgerId, entryId, status, response); response.release(); response.recycle(); recycle(); } void recycle() { completionValue = null; ledgerId = -1; entryId = -1; status = null; response = null; recyclerHandle.recycle(this); } private final Handle<ReadV2ResponseCallback> recyclerHandle; private ReadV2ResponseCallback(Handle<ReadV2ResponseCallback> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ReadV2ResponseCallback> RECYCLER = new Recycler<ReadV2ResponseCallback>() { @Override protected ReadV2ResponseCallback newObject(Handle<ReadV2ResponseCallback> handle) { return new ReadV2ResponseCallback(handle); } }; } private static OperationType getOperationType(byte opCode) { switch (opCode) { case BookieProtocol.ADDENTRY: return OperationType.ADD_ENTRY; case BookieProtocol.READENTRY: return OperationType.READ_ENTRY; case BookieProtocol.AUTH: return OperationType.AUTH; case BookieProtocol.READ_LAC: return OperationType.READ_LAC; case BookieProtocol.WRITE_LAC: return OperationType.WRITE_LAC; case BookieProtocol.GET_BOOKIE_INFO: return OperationType.GET_BOOKIE_INFO; default: throw new IllegalArgumentException("Invalid operation type " + opCode); } } private static StatusCode getStatusCodeFromErrorCode(int errorCode) { switch (errorCode) { case BookieProtocol.EOK: return StatusCode.EOK; case BookieProtocol.ENOLEDGER: return StatusCode.ENOLEDGER; case BookieProtocol.ENOENTRY: return StatusCode.ENOENTRY; case BookieProtocol.EBADREQ: return StatusCode.EBADREQ; case BookieProtocol.EIO: return StatusCode.EIO; case BookieProtocol.EUA: return StatusCode.EUA; case BookieProtocol.EBADVERSION: return StatusCode.EBADVERSION; case BookieProtocol.EFENCED: return StatusCode.EFENCED; case BookieProtocol.EREADONLY: return StatusCode.EREADONLY; case BookieProtocol.ETOOMANYREQUESTS: return StatusCode.ETOOMANYREQUESTS; default: throw new IllegalArgumentException("Invalid error code: " + errorCode); } } private void readV3Response(final Response response) { final BKPacketHeader header = response.getHeader(); final CompletionKey key = newCompletionKey(header.getTxnId(), header.getOperation()); final CompletionValue completionValue = completionObjects.get(key); if (null == completionValue) { // Unexpected response, so log it. The txnId should have been present. if (LOG.isDebugEnabled()) { LOG.debug("Unexpected response received from bookie : " + bookieId + " for type : " + header.getOperation() + " and txnId : " + header.getTxnId()); } } else { long orderingKey = completionValue.ledgerId; executor.executeOrdered(orderingKey, new Runnable() { @Override public void run() { completionValue.restoreMdcContext(); completionValue.handleV3Response(response); } @Override public String toString() { return String.format("HandleResponse(Txn=%d, Type=%s, Entry=(%d, %d))", header.getTxnId(), header.getOperation(), completionValue.ledgerId, completionValue.entryId); } }); } completionObjects.remove(key); } void initTLSHandshake() { // create TLS handler PerChannelBookieClient parentObj = PerChannelBookieClient.this; SocketAddress socketAddress = channel.remoteAddress(); InetSocketAddress address; if (socketAddress instanceof LocalAddress) { // if it is a local address, it looks like this: local:hostname:port String[] addr = socketAddress.toString().split(":"); String hostname = addr[1]; int port = Integer.parseInt(addr[2]); address = new InetSocketAddress(hostname, port); } else if (socketAddress instanceof InetSocketAddress) { address = (InetSocketAddress) socketAddress; } else { throw new RuntimeException("Unexpected socket address type"); } SslHandler handler = parentObj.shFactory.newTLSHandler(address.getHostName(), address.getPort()); channel.pipeline().addFirst(parentObj.shFactory.getHandlerName(), handler); handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { int rc; Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps; synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING) { LOG.error("Connection state changed before TLS handshake completed {}/{}", bookieId, state); rc = BKException.Code.BookieHandleNotAvailableException; closeChannel(channel); channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } } else if (future.isSuccess() && state == ConnectionState.START_TLS) { rc = BKException.Code.OK; LOG.info("Successfully connected to bookie using TLS: " + bookieId); state = ConnectionState.CONNECTED; AuthHandler.ClientSideHandler authHandler = future.get().pipeline() .get(AuthHandler.ClientSideHandler.class); authHandler.authProvider.onProtocolUpgrade(); activeTlsChannelCounter.inc(); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.warn("Closed before TLS handshake completed, clean up: {}, current state {}", channel, state); closeChannel(channel); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { if (LOG.isDebugEnabled()) { LOG.debug("Already connected with another channel({}), " + "so close the new channel({})", channel, channel); } closeChannel(channel); return; // pendingOps should have been completed when other channel connected } else { LOG.error("TLS handshake failed with bookie: {}/{}, current state {} : ", channel, bookieId, state, future.cause()); rc = BKException.Code.SecurityException; closeChannel(channel); channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } failedTlsHandshakeCounter.inc(); } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<>(); } makeWritable(); for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, PerChannelBookieClient.this); } } }); } /** * Boiler-plate wrapper classes follow. * */ // visible for testing abstract class CompletionValue { private final OpStatsLogger opLogger; private final OpStatsLogger timeoutOpLogger; private final String operationName; private final Map<String, String> mdcContextMap; protected Object ctx; protected long ledgerId; protected long entryId; protected long startTime; public CompletionValue(String operationName, Object ctx, long ledgerId, long entryId, OpStatsLogger opLogger, OpStatsLogger timeoutOpLogger) { this.operationName = operationName; this.ctx = ctx; this.ledgerId = ledgerId; this.entryId = entryId; this.startTime = MathUtils.nowInNano(); this.opLogger = opLogger; this.timeoutOpLogger = timeoutOpLogger; this.mdcContextMap = preserveMdcForTaskExecution ? MDC.getCopyOfContextMap() : null; } private long latency() { return MathUtils.elapsedNanos(startTime); } void logOpResult(int rc) { if (rc != BKException.Code.OK) { opLogger.registerFailedEvent(latency(), TimeUnit.NANOSECONDS); } else { opLogger.registerSuccessfulEvent(latency(), TimeUnit.NANOSECONDS); } if (rc != BKException.Code.OK && !expectedBkOperationErrors.contains(rc)) { recordError(); } } boolean maybeTimeout() { if (MathUtils.elapsedNanos(startTime) >= readEntryTimeoutNanos) { timeout(); return true; } else { return false; } } void timeout() { errorOut(BKException.Code.TimeoutException); timeoutOpLogger.registerSuccessfulEvent(latency(), TimeUnit.NANOSECONDS); } protected void logResponse(StatusCode status, Object... extraInfo) { if (LOG.isDebugEnabled()) { LOG.debug("Got {} response from bookie:{} rc:{}, {}", operationName, bookieId, status, Joiner.on(":").join(extraInfo)); } } protected int convertStatus(StatusCode status, int defaultStatus) { // convert to BKException code int rcToRet = statusCodeToExceptionCode(status); if (rcToRet == BKException.Code.UNINITIALIZED) { LOG.error("{} for failed on bookie {} code {}", operationName, bookieId, status); return defaultStatus; } else { return rcToRet; } } public void restoreMdcContext() { MdcUtils.restoreContext(mdcContextMap); } public abstract void errorOut(); public abstract void errorOut(int rc); public void setOutstanding() { // no-op } protected void errorOutAndRunCallback(final Runnable callback) { executor.executeOrdered(ledgerId, () -> { String bAddress = "null"; Channel c = channel; if (c != null && c.remoteAddress() != null) { bAddress = c.remoteAddress().toString(); } if (LOG.isDebugEnabled()) { LOG.debug("Could not write {} request to bookie {} for ledger {}, entry {}", operationName, bAddress, ledgerId, entryId); } callback.run(); }); } public void handleV2Response( long ledgerId, long entryId, StatusCode status, BookieProtocol.Response response) { LOG.warn("Unhandled V2 response {}", response); } public abstract void handleV3Response( BookkeeperProtocol.Response response); } // visible for testing class WriteLacCompletion extends CompletionValue { final WriteLacCallback cb; public WriteLacCompletion(final CompletionKey key, final WriteLacCallback originalCallback, final Object originalCtx, final long ledgerId) { super("WriteLAC", originalCtx, ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, writeLacOpLogger, writeLacTimeoutOpLogger); this.cb = new WriteLacCallback() { @Override public void writeLacComplete(int rc, long ledgerId, BookieId addr, Object ctx) { logOpResult(rc); originalCallback.writeLacComplete(rc, ledgerId, addr, originalCtx); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> cb.writeLacComplete(rc, ledgerId, bookieId, ctx)); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { WriteLacResponse writeLacResponse = response.getWriteLacResponse(); StatusCode status = response.getStatus() == StatusCode.EOK ? writeLacResponse.getStatus() : response.getStatus(); long ledgerId = writeLacResponse.getLedgerId(); if (LOG.isDebugEnabled()) { logResponse(status, "ledger", ledgerId); } int rc = convertStatus(status, BKException.Code.WriteException); cb.writeLacComplete(rc, ledgerId, bookieId, ctx); } } class ForceLedgerCompletion extends CompletionValue { final ForceLedgerCallback cb; public ForceLedgerCompletion(final CompletionKey key, final ForceLedgerCallback originalCallback, final Object originalCtx, final long ledgerId) { super("ForceLedger", originalCtx, ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, forceLedgerOpLogger, forceLedgerTimeoutOpLogger); this.cb = new ForceLedgerCallback() { @Override public void forceLedgerComplete(int rc, long ledgerId, BookieId addr, Object ctx) { logOpResult(rc); originalCallback.forceLedgerComplete(rc, ledgerId, addr, originalCtx); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> cb.forceLedgerComplete(rc, ledgerId, bookieId, ctx)); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { ForceLedgerResponse forceLedgerResponse = response.getForceLedgerResponse(); StatusCode status = response.getStatus() == StatusCode.EOK ? forceLedgerResponse.getStatus() : response.getStatus(); long ledgerId = forceLedgerResponse.getLedgerId(); if (LOG.isDebugEnabled()) { logResponse(status, "ledger", ledgerId); } int rc = convertStatus(status, BKException.Code.WriteException); cb.forceLedgerComplete(rc, ledgerId, bookieId, ctx); } } // visible for testing class ReadLacCompletion extends CompletionValue { final ReadLacCallback cb; public ReadLacCompletion(final CompletionKey key, ReadLacCallback originalCallback, final Object ctx, final long ledgerId) { super("ReadLAC", ctx, ledgerId, BookieProtocol.LAST_ADD_CONFIRMED, readLacOpLogger, readLacTimeoutOpLogger); this.cb = new ReadLacCallback() { @Override public void readLacComplete(int rc, long ledgerId, ByteBuf lacBuffer, ByteBuf lastEntryBuffer, Object ctx) { logOpResult(rc); originalCallback.readLacComplete( rc, ledgerId, lacBuffer, lastEntryBuffer, ctx); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> cb.readLacComplete(rc, ledgerId, null, null, ctx)); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { ReadLacResponse readLacResponse = response.getReadLacResponse(); ByteBuf lacBuffer = Unpooled.EMPTY_BUFFER; ByteBuf lastEntryBuffer = Unpooled.EMPTY_BUFFER; StatusCode status = response.getStatus() == StatusCode.EOK ? readLacResponse.getStatus() : response.getStatus(); if (readLacResponse.hasLacBody()) { lacBuffer = Unpooled.wrappedBuffer(readLacResponse.getLacBody().asReadOnlyByteBuffer()); } if (readLacResponse.hasLastEntryBody()) { lastEntryBuffer = Unpooled.wrappedBuffer(readLacResponse.getLastEntryBody().asReadOnlyByteBuffer()); } if (LOG.isDebugEnabled()) { logResponse(status, "ledgerId", ledgerId); } int rc = convertStatus(status, BKException.Code.ReadException); cb.readLacComplete(rc, ledgerId, lacBuffer.slice(), lastEntryBuffer.slice(), ctx); } } // visible for testing class ReadCompletion extends CompletionValue { final ReadEntryCallback cb; public ReadCompletion(final CompletionKey key, final ReadEntryCallback originalCallback, final Object originalCtx, long ledgerId, final long entryId) { super("Read", originalCtx, ledgerId, entryId, readEntryOpLogger, readTimeoutOpLogger); this.cb = new ReadEntryCallback() { @Override public void readEntryComplete(int rc, long ledgerId, long entryId, ByteBuf buffer, Object ctx) { logOpResult(rc); originalCallback.readEntryComplete(rc, ledgerId, entryId, buffer, originalCtx); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> cb.readEntryComplete(rc, ledgerId, entryId, null, ctx)); } @Override public void setOutstanding() { readEntryOutstanding.inc(); } @Override public void handleV2Response(long ledgerId, long entryId, StatusCode status, BookieProtocol.Response response) { readEntryOutstanding.dec(); if (!(response instanceof BookieProtocol.ReadResponse)) { return; } BookieProtocol.ReadResponse readResponse = (BookieProtocol.ReadResponse) response; handleReadResponse(ledgerId, entryId, status, readResponse.getData(), INVALID_ENTRY_ID, -1L); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { readEntryOutstanding.dec(); ReadResponse readResponse = response.getReadResponse(); StatusCode status = response.getStatus() == StatusCode.EOK ? readResponse.getStatus() : response.getStatus(); ByteBuf buffer = Unpooled.EMPTY_BUFFER; if (readResponse.hasBody()) { buffer = Unpooled.wrappedBuffer(readResponse.getBody().asReadOnlyByteBuffer()); } long maxLAC = INVALID_ENTRY_ID; if (readResponse.hasMaxLAC()) { maxLAC = readResponse.getMaxLAC(); } long lacUpdateTimestamp = -1L; if (readResponse.hasLacUpdateTimestamp()) { lacUpdateTimestamp = readResponse.getLacUpdateTimestamp(); } handleReadResponse(readResponse.getLedgerId(), readResponse.getEntryId(), status, buffer, maxLAC, lacUpdateTimestamp); ReferenceCountUtil.release( buffer); // meaningless using unpooled, but client may expect to hold the last reference } private void handleReadResponse(long ledgerId, long entryId, StatusCode status, ByteBuf buffer, long maxLAC, // max known lac piggy-back from bookies long lacUpdateTimestamp) { // the timestamp when the lac is updated. int readableBytes = buffer.readableBytes(); if (LOG.isDebugEnabled()) { logResponse(status, "ledger", ledgerId, "entry", entryId, "entryLength", readableBytes); } int rc = convertStatus(status, BKException.Code.ReadException); if (maxLAC > INVALID_ENTRY_ID && (ctx instanceof ReadEntryCallbackCtx)) { ((ReadEntryCallbackCtx) ctx).setLastAddConfirmed(maxLAC); } if (lacUpdateTimestamp > -1L && (ctx instanceof ReadLastConfirmedAndEntryContext)) { ((ReadLastConfirmedAndEntryContext) ctx).setLacUpdateTimestamp(lacUpdateTimestamp); } cb.readEntryComplete(rc, ledgerId, entryId, buffer.slice(), ctx); } } class StartTLSCompletion extends CompletionValue { final StartTLSCallback cb; public StartTLSCompletion(final CompletionKey key) { super("StartTLS", null, -1, -1, startTLSOpLogger, startTLSTimeoutOpLogger); this.cb = new StartTLSCallback() { @Override public void startTLSComplete(int rc, Object ctx) { logOpResult(rc); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { failTLS(rc); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { StatusCode status = response.getStatus(); if (LOG.isDebugEnabled()) { logResponse(status); } int rc = convertStatus(status, BKException.Code.SecurityException); // Cancel START_TLS request timeout cb.startTLSComplete(rc, null); if (state != ConnectionState.START_TLS) { LOG.error("Connection state changed before TLS response received"); failTLS(BKException.Code.BookieHandleNotAvailableException); } else if (status != StatusCode.EOK) { LOG.error("Client received error {} during TLS negotiation", status); failTLS(BKException.Code.SecurityException); } else { initTLSHandshake(); } } } // visible for testing class GetBookieInfoCompletion extends CompletionValue { final GetBookieInfoCallback cb; public GetBookieInfoCompletion(final CompletionKey key, final GetBookieInfoCallback origCallback, final Object origCtx) { super("GetBookieInfo", origCtx, 0L, 0L, getBookieInfoOpLogger, getBookieInfoTimeoutOpLogger); this.cb = new GetBookieInfoCallback() { @Override public void getBookieInfoComplete(int rc, BookieInfo bInfo, Object ctx) { logOpResult(rc); origCallback.getBookieInfoComplete(rc, bInfo, origCtx); key.release(); } }; } @Override boolean maybeTimeout() { if (MathUtils.elapsedNanos(startTime) >= getBookieInfoTimeoutNanos) { timeout(); return true; } else { return false; } } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> cb.getBookieInfoComplete(rc, new BookieInfo(), ctx)); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { GetBookieInfoResponse getBookieInfoResponse = response.getGetBookieInfoResponse(); StatusCode status = response.getStatus() == StatusCode.EOK ? getBookieInfoResponse.getStatus() : response.getStatus(); long freeDiskSpace = getBookieInfoResponse.getFreeDiskSpace(); long totalDiskSpace = getBookieInfoResponse.getTotalDiskCapacity(); if (LOG.isDebugEnabled()) { logResponse(status, "freeDisk", freeDiskSpace, "totalDisk", totalDiskSpace); } int rc = convertStatus(status, BKException.Code.ReadException); cb.getBookieInfoComplete(rc, new BookieInfo(totalDiskSpace, freeDiskSpace), ctx); } } class GetListOfEntriesOfLedgerCompletion extends CompletionValue { final GetListOfEntriesOfLedgerCallback cb; public GetListOfEntriesOfLedgerCompletion(final CompletionKey key, final GetListOfEntriesOfLedgerCallback origCallback, final long ledgerId) { super("GetListOfEntriesOfLedger", null, ledgerId, 0L, getListOfEntriesOfLedgerCompletionOpLogger, getListOfEntriesOfLedgerCompletionTimeoutOpLogger); this.cb = new GetListOfEntriesOfLedgerCallback() { @Override public void getListOfEntriesOfLedgerComplete(int rc, long ledgerId, AvailabilityOfEntriesOfLedger availabilityOfEntriesOfLedger) { logOpResult(rc); origCallback.getListOfEntriesOfLedgerComplete(rc, ledgerId, availabilityOfEntriesOfLedger); key.release(); } }; } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback(() -> cb.getListOfEntriesOfLedgerComplete(rc, ledgerId, null)); } @Override public void handleV3Response(BookkeeperProtocol.Response response) { GetListOfEntriesOfLedgerResponse getListOfEntriesOfLedgerResponse = response .getGetListOfEntriesOfLedgerResponse(); ByteBuf availabilityOfEntriesOfLedgerBuffer = Unpooled.EMPTY_BUFFER; StatusCode status = response.getStatus() == StatusCode.EOK ? getListOfEntriesOfLedgerResponse.getStatus() : response.getStatus(); if (getListOfEntriesOfLedgerResponse.hasAvailabilityOfEntriesOfLedger()) { availabilityOfEntriesOfLedgerBuffer = Unpooled.wrappedBuffer( getListOfEntriesOfLedgerResponse.getAvailabilityOfEntriesOfLedger().asReadOnlyByteBuffer()); } if (LOG.isDebugEnabled()) { logResponse(status, "ledgerId", ledgerId); } int rc = convertStatus(status, BKException.Code.ReadException); AvailabilityOfEntriesOfLedger availabilityOfEntriesOfLedger = null; if (rc == BKException.Code.OK) { availabilityOfEntriesOfLedger = new AvailabilityOfEntriesOfLedger( availabilityOfEntriesOfLedgerBuffer.slice()); } cb.getListOfEntriesOfLedgerComplete(rc, ledgerId, availabilityOfEntriesOfLedger); } } private final Recycler<AddCompletion> addCompletionRecycler = new Recycler<AddCompletion>() { @Override protected AddCompletion newObject(Recycler.Handle<AddCompletion> handle) { return new AddCompletion(handle); } }; AddCompletion acquireAddCompletion(final CompletionKey key, final WriteCallback originalCallback, final Object originalCtx, final long ledgerId, final long entryId) { AddCompletion completion = addCompletionRecycler.get(); completion.reset(key, originalCallback, originalCtx, ledgerId, entryId); return completion; } // visible for testing class AddCompletion extends CompletionValue implements WriteCallback { final Recycler.Handle<AddCompletion> handle; CompletionKey key = null; WriteCallback originalCallback = null; AddCompletion(Recycler.Handle<AddCompletion> handle) { super("Add", null, -1, -1, addEntryOpLogger, addTimeoutOpLogger); this.handle = handle; } void reset(final CompletionKey key, final WriteCallback originalCallback, final Object originalCtx, final long ledgerId, final long entryId) { this.key = key; this.originalCallback = originalCallback; this.ctx = originalCtx; this.ledgerId = ledgerId; this.entryId = entryId; this.startTime = MathUtils.nowInNano(); } @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) { logOpResult(rc); originalCallback.writeComplete(rc, ledgerId, entryId, addr, ctx); key.release(); handle.recycle(this); } @Override boolean maybeTimeout() { if (MathUtils.elapsedNanos(startTime) >= addEntryTimeoutNanos) { timeout(); return true; } else { return false; } } @Override public void errorOut() { errorOut(BKException.Code.BookieHandleNotAvailableException); } @Override public void errorOut(final int rc) { errorOutAndRunCallback( () -> writeComplete(rc, ledgerId, entryId, bookieId, ctx)); } @Override public void setOutstanding() { addEntryOutstanding.inc(); } @Override public void handleV2Response( long ledgerId, long entryId, StatusCode status, BookieProtocol.Response response) { addEntryOutstanding.dec(); handleResponse(ledgerId, entryId, status); } @Override public void handleV3Response( BookkeeperProtocol.Response response) { addEntryOutstanding.dec(); AddResponse addResponse = response.getAddResponse(); StatusCode status = response.getStatus() == StatusCode.EOK ? addResponse.getStatus() : response.getStatus(); handleResponse(addResponse.getLedgerId(), addResponse.getEntryId(), status); } private void handleResponse(long ledgerId, long entryId, StatusCode status) { if (LOG.isDebugEnabled()) { logResponse(status, "ledger", ledgerId, "entry", entryId); } int rc = convertStatus(status, BKException.Code.WriteException); writeComplete(rc, ledgerId, entryId, bookieId, ctx); } } // visable for testing CompletionKey newCompletionKey(long txnId, OperationType operationType) { return new V3CompletionKey(txnId, operationType); } class V3CompletionKey extends CompletionKey { public V3CompletionKey(long txnId, OperationType operationType) { super(txnId, operationType); } @Override public boolean equals(Object obj) { if (!(obj instanceof V3CompletionKey)) { return false; } V3CompletionKey that = (V3CompletionKey) obj; return this.txnId == that.txnId && this.operationType == that.operationType; } @Override public int hashCode() { return ((int) txnId); } @Override public String toString() { return String.format("TxnId(%d), OperationType(%s)", txnId, operationType); } } abstract class CompletionKey { final long txnId; OperationType operationType; CompletionKey(long txnId, OperationType operationType) { this.txnId = txnId; this.operationType = operationType; } public void release() {} } /** * Note : Helper functions follow */ /** * @param status * @return {@link BKException.Code.UNINITIALIZED} if the statuscode is unknown. */ private int statusCodeToExceptionCode(StatusCode status) { switch (status) { case EOK: return BKException.Code.OK; case ENOENTRY: return BKException.Code.NoSuchEntryException; case ENOLEDGER: return BKException.Code.NoSuchLedgerExistsException; case EBADVERSION: return BKException.Code.ProtocolVersionException; case EUA: return BKException.Code.UnauthorizedAccessException; case EFENCED: return BKException.Code.LedgerFencedException; case EREADONLY: return BKException.Code.WriteOnReadOnlyBookieException; case ETOOMANYREQUESTS: return BKException.Code.TooManyRequestsException; case EUNKNOWNLEDGERSTATE: return BKException.Code.DataUnknownException; default: return BKException.Code.UNINITIALIZED; } } private void putCompletionKeyValue(CompletionKey key, CompletionValue value) { CompletionValue existingValue = completionObjects.putIfAbsent(key, value); if (existingValue != null) { // will only happen for V2 keys, as V3 have unique txnid // There's a pending read request on same ledger/entry. Use the multimap to track all of them completionObjectsV2Conflicts.put(key, value); } } private CompletionValue getCompletionValue(CompletionKey key) { CompletionValue completionValue = completionObjects.remove(key); if (completionValue == null) { // If there's no completion object here, try in the multimap completionValue = completionObjectsV2Conflicts.removeAny(key).orElse(null); } return completionValue; } private long getTxnId() { return txnIdGenerator.incrementAndGet(); } private final Recycler<V2CompletionKey> v2KeyRecycler = new Recycler<V2CompletionKey>() { @Override protected V2CompletionKey newObject( Recycler.Handle<V2CompletionKey> handle) { return new V2CompletionKey(handle); } }; V2CompletionKey acquireV2Key(long ledgerId, long entryId, OperationType operationType) { V2CompletionKey key = v2KeyRecycler.get(); key.reset(ledgerId, entryId, operationType); return key; } private class V2CompletionKey extends CompletionKey { private final Handle<V2CompletionKey> recyclerHandle; long ledgerId; long entryId; private V2CompletionKey(Handle<V2CompletionKey> handle) { super(-1, null); this.recyclerHandle = handle; } void reset(long ledgerId, long entryId, OperationType operationType) { this.ledgerId = ledgerId; this.entryId = entryId; this.operationType = operationType; } @Override public boolean equals(Object object) { if (!(object instanceof V2CompletionKey)) { return false; } V2CompletionKey that = (V2CompletionKey) object; return this.entryId == that.entryId && this.ledgerId == that.ledgerId && this.operationType == that.operationType; } @Override public int hashCode() { return Long.hashCode(ledgerId) * 31 + Long.hashCode(entryId); } @Override public String toString() { return String.format("%d:%d %s", ledgerId, entryId, operationType); } @Override public void release() { recyclerHandle.recycle(this); } } Request.Builder withRequestContext(Request.Builder builder) { if (preserveMdcForTaskExecution) { return appendRequestContext(builder); } return builder; } static Request.Builder appendRequestContext(Request.Builder builder) { final Map<String, String> mdcContextMap = MDC.getCopyOfContextMap(); if (mdcContextMap == null || mdcContextMap.isEmpty()) { return builder; } for (Map.Entry<String, String> kv : mdcContextMap.entrySet()) { final BookkeeperProtocol.ContextPair context = BookkeeperProtocol.ContextPair.newBuilder() .setKey(kv.getKey()) .setValue(kv.getValue()) .build(); builder.addRequestContext(context); } return builder; } ChannelFutureListener contextPreservingListener(ChannelFutureListener listener) { return preserveMdcForTaskExecution ? new ContextPreservingFutureListener(listener) : listener; } /** * Decorator to preserve MDC for connection listener. */ static class ContextPreservingFutureListener implements ChannelFutureListener { private final ChannelFutureListener listener; private final Map<String, String> mdcContextMap; ContextPreservingFutureListener(ChannelFutureListener listener) { this.listener = listener; this.mdcContextMap = MDC.getCopyOfContextMap(); } @Override public void operationComplete(ChannelFuture future) throws Exception { MdcUtils.restoreContext(mdcContextMap); try { listener.operationComplete(future); } finally { MDC.clear(); } } } /** * Connection listener. */ class ConnectionFutureListener implements ChannelFutureListener { private final long startTime; ConnectionFutureListener(long startTime) { this.startTime = startTime; } @Override public void operationComplete(ChannelFuture future) { if (LOG.isDebugEnabled()) { LOG.debug("Channel connected ({}) {}", future.isSuccess(), future.channel()); } int rc; Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps; /* We fill in the timer based on whether the connect operation itself succeeded regardless of * whether there was a race */ if (future.isSuccess()) { PerChannelBookieClient.this .connectTimer.registerSuccessfulEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } else { PerChannelBookieClient.this .connectTimer.registerFailedEvent(MathUtils.elapsedNanos(startTime), TimeUnit.NANOSECONDS); } synchronized (PerChannelBookieClient.this) { if (future.isSuccess() && state == ConnectionState.CONNECTING && future.channel().isActive()) { rc = BKException.Code.OK; channel = future.channel(); if (shFactory != null) { LOG.info("Successfully connected to bookie: {} {} initiate TLS", bookieId, future.channel()); makeWritable(); initiateTLS(); return; } else { LOG.info("Successfully connected to bookie: {} {}", bookieId, future.channel()); state = ConnectionState.CONNECTED; activeNonTlsChannelCounter.inc(); } } else if (future.isSuccess() && state == ConnectionState.START_TLS) { rc = BKException.Code.OK; LOG.info("Successfully connected to bookie using TLS: " + bookieId); state = ConnectionState.CONNECTED; AuthHandler.ClientSideHandler authHandler = future.channel().pipeline() .get(AuthHandler.ClientSideHandler.class); authHandler.authProvider.onProtocolUpgrade(); activeTlsChannelCounter.inc(); } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) { LOG.warn("Closed before connection completed, clean up: {}, current state {}", future.channel(), state); closeChannel(future.channel()); rc = BKException.Code.BookieHandleNotAvailableException; channel = null; } else if (future.isSuccess() && state == ConnectionState.CONNECTED) { if (LOG.isDebugEnabled()) { LOG.debug("Already connected with another channel({}), so close the new channel({})", channel, future.channel()); } closeChannel(future.channel()); return; // pendingOps should have been completed when other channel connected } else { Throwable cause = future.cause(); if (cause instanceof UnknownHostException || cause instanceof NativeIoException) { // Don't log stack trace for common errors logBookieUnavailable(() -> LOG.warn("Could not connect to bookie: {}/{}, current state {} : {}", future.channel(), bookieId, state, future.cause().getMessage())); } else { // Regular exceptions, include stack trace logBookieUnavailable(() -> LOG.error("Could not connect to bookie: {}/{}, current state {} : ", future.channel(), bookieId, state, future.cause())); } rc = BKException.Code.BookieHandleNotAvailableException; Channel failedChannel = future.channel(); if (failedChannel != null) { // can be null in case of dummy failed ChannelFuture closeChannel(failedChannel); } channel = null; if (state != ConnectionState.CLOSED) { state = ConnectionState.DISCONNECTED; } failedConnectionCounter.inc(); } // trick to not do operations under the lock, take the list // of pending ops and assign it to a new variable, while // emptying the pending ops by just assigning it to a new // list oldPendingOps = pendingOps; pendingOps = new ArrayDeque<>(); } for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, PerChannelBookieClient.this); } makeWritable(); } private void logBookieUnavailable(Runnable logger) { final long now = System.currentTimeMillis(); if ((now - lastBookieUnavailableLogTimestamp) > conf.getClientConnectBookieUnavailableLogThrottlingMs()) { logger.run(); lastBookieUnavailableLogTimestamp = now; } } } private void initiateTLS() { LOG.info("Initializing TLS to {}", channel); assert state == ConnectionState.CONNECTING; final long txnId = getTxnId(); final CompletionKey completionKey = new V3CompletionKey(txnId, OperationType.START_TLS); completionObjects.put(completionKey, new StartTLSCompletion(completionKey)); BookkeeperProtocol.Request.Builder h = withRequestContext(BookkeeperProtocol.Request.newBuilder()); BKPacketHeader.Builder headerBuilder = BKPacketHeader.newBuilder() .setVersion(ProtocolVersion.VERSION_THREE) .setOperation(OperationType.START_TLS) .setTxnId(txnId); h.setHeader(headerBuilder.build()); h.setStartTLSRequest(BookkeeperProtocol.StartTLSRequest.newBuilder().build()); state = ConnectionState.START_TLS; writeAndFlush(channel, completionKey, h.build()); } private void failTLS(int rc) { LOG.error("TLS failure on: {}, rc: {}", channel, rc); Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps; synchronized (this) { disconnect(); oldPendingOps = pendingOps; pendingOps = new ArrayDeque<>(); } for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) { pendingOp.operationComplete(rc, null); } failedTlsHandshakeCounter.inc(); } private static class FailedChannelFutureImpl implements ChannelFuture { private final Throwable failureCause; public FailedChannelFutureImpl(Throwable failureCause) { this.failureCause = failureCause; } @Override public Channel channel() { // used only for log return null; } @Override public ChannelFuture addListener(GenericFutureListener<? extends Future<? super Void>> listener) { throw new UnsupportedOperationException("Not supported"); } @Override @SuppressWarnings({"unchecked", "varargs"}) public ChannelFuture addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { throw new UnsupportedOperationException("Not supported"); } @Override public ChannelFuture removeListener(GenericFutureListener<? extends Future<? super Void>> listener) { throw new UnsupportedOperationException("Not supported"); } @Override @SuppressWarnings({"unchecked", "varargs"}) public ChannelFuture removeListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) { throw new UnsupportedOperationException("Not supported"); } @Override public ChannelFuture sync() throws InterruptedException { throw new UnsupportedOperationException("Not supported"); } @Override public ChannelFuture syncUninterruptibly() { throw new UnsupportedOperationException("Not supported"); } @Override public ChannelFuture await() throws InterruptedException { throw new UnsupportedOperationException("Not supported"); } @Override public ChannelFuture awaitUninterruptibly() { throw new UnsupportedOperationException("Not supported"); } @Override public boolean isVoid() { throw new UnsupportedOperationException("Not supported"); } @Override public boolean isSuccess() { return false; } @Override public boolean isCancellable() { return false; } @Override public Throwable cause() { return failureCause; } @Override public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return true; } @Override public boolean await(long timeoutMillis) throws InterruptedException { return true; } @Override public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { return true; } @Override public boolean awaitUninterruptibly(long timeoutMillis) { return true; } @Override public Void getNow() { throw new UnsupportedOperationException("Not supported"); } @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; } @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { return true; } @Override public Void get() throws InterruptedException, ExecutionException { throw new ExecutionException(failureCause); } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { throw new ExecutionException(failureCause); } } }
74
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/WriteEntryProcessor.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.proto; import com.google.common.annotations.VisibleForTesting; import io.netty.buffer.ByteBuf; import io.netty.util.Recycler; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.OperationRejectedException; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookieProtocol.ParsedAddRequest; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Processes add entry requests. */ class WriteEntryProcessor extends PacketProcessorBase<ParsedAddRequest> implements WriteCallback { private static final Logger LOG = LoggerFactory.getLogger(WriteEntryProcessor.class); long startTimeNanos; @Override protected void reset() { super.reset(); startTimeNanos = -1L; } public static WriteEntryProcessor create(ParsedAddRequest request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { WriteEntryProcessor wep = RECYCLER.get(); wep.init(request, requestHandler, requestProcessor); requestProcessor.onAddRequestStart(requestHandler.ctx().channel()); return wep; } @Override protected void processPacket() { if (requestProcessor.getBookie().isReadOnly() && !(request.isHighPriority() && requestProcessor.getBookie().isAvailableForHighPriorityWrites())) { LOG.warn("BookieServer is running in readonly mode," + " so rejecting the request from the client!"); sendWriteReqResponse(BookieProtocol.EREADONLY, ResponseBuilder.buildErrorResponse(BookieProtocol.EREADONLY, request), requestProcessor.getRequestStats().getAddRequestStats()); request.release(); request.recycle(); recycle(); return; } startTimeNanos = MathUtils.nowInNano(); int rc = BookieProtocol.EOK; ByteBuf addData = request.getData(); try { if (request.isRecoveryAdd()) { requestProcessor.getBookie().recoveryAddEntry(addData, this, requestHandler, request.getMasterKey()); } else { requestProcessor.getBookie().addEntry(addData, false, this, requestHandler, request.getMasterKey()); } } catch (OperationRejectedException e) { requestProcessor.getRequestStats().getAddEntryRejectedCounter().inc(); // Avoid to log each occurence of this exception as this can happen when the ledger storage is // unable to keep up with the write rate. if (LOG.isDebugEnabled()) { LOG.debug("Operation rejected while writing {}", request, e); } rc = BookieProtocol.ETOOMANYREQUESTS; } catch (IOException e) { LOG.error("Error writing {}", request, e); rc = BookieProtocol.EIO; } catch (BookieException.LedgerFencedException lfe) { LOG.error("Attempt to write to fenced ledger", lfe); rc = BookieProtocol.EFENCED; } catch (BookieException e) { LOG.error("Unauthorized access to ledger {}", request.getLedgerId(), e); rc = BookieProtocol.EUA; } catch (Throwable t) { LOG.error("Unexpected exception while writing {}@{} : {}", request.ledgerId, request.entryId, t.getMessage(), t); // some bad request which cause unexpected exception rc = BookieProtocol.EBADREQ; } if (rc != BookieProtocol.EOK) { requestProcessor.getRequestStats().getAddEntryStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); sendWriteReqResponse(rc, ResponseBuilder.buildErrorResponse(rc, request), requestProcessor.getRequestStats().getAddRequestStats()); request.recycle(); recycle(); } } @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) { if (BookieProtocol.EOK == rc) { requestProcessor.getRequestStats().getAddEntryStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getAddEntryStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } requestHandler.prepareSendResponseV2(rc, request); requestProcessor.onAddRequestFinish(); request.recycle(); recycle(); } @Override public String toString() { return String.format("WriteEntry(%d, %d)", request.getLedgerId(), request.getEntryId()); } @VisibleForTesting void recycle() { reset(); recyclerHandle.recycle(this); } private final Recycler.Handle<WriteEntryProcessor> recyclerHandle; private WriteEntryProcessor(Recycler.Handle<WriteEntryProcessor> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<WriteEntryProcessor> RECYCLER = new Recycler<WriteEntryProcessor>() { @Override protected WriteEntryProcessor newObject(Recycler.Handle<WriteEntryProcessor> handle) { return new WriteEntryProcessor(handle); } }; }
75
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ClientConnectionPeer.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.proto; /** * Represents the connection to a Bookie, from the client side. */ public interface ClientConnectionPeer extends ConnectionPeer { }
76
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BKStats.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.proto; import java.beans.ConstructorProperties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Bookie Server Stats. */ public class BKStats { private static final Logger LOG = LoggerFactory.getLogger(BKStats.class); private static BKStats instance = new BKStats(); public static BKStats getInstance() { return instance; } /** * A read view of stats, also used in CompositeViewData to expose to JMX. */ public static class OpStatData { private final long maxLatency, minLatency; private final double avgLatency; private final long numSuccessOps, numFailedOps; private final String latencyHist; @ConstructorProperties({"maxLatency", "minLatency", "avgLatency", "numSuccessOps", "numFailedOps", "latencyHist"}) public OpStatData(long maxLatency, long minLatency, double avgLatency, long numSuccessOps, long numFailedOps, String latencyHist) { this.maxLatency = maxLatency; this.minLatency = minLatency == Long.MAX_VALUE ? 0 : minLatency; this.avgLatency = avgLatency; this.numSuccessOps = numSuccessOps; this.numFailedOps = numFailedOps; this.latencyHist = latencyHist; } public long getMaxLatency() { return maxLatency; } public long getMinLatency() { return minLatency; } public double getAvgLatency() { return avgLatency; } public long getNumSuccessOps() { return numSuccessOps; } public long getNumFailedOps() { return numFailedOps; } public String getLatencyHist() { return latencyHist; } } /** * Operation Statistics. */ public static class OpStats { static final int NUM_BUCKETS = 3 * 9 + 2; long maxLatency = 0; long minLatency = Long.MAX_VALUE; double totalLatency = 0.0f; long numSuccessOps = 0; long numFailedOps = 0; long[] latencyBuckets = new long[NUM_BUCKETS]; OpStats() {} /** * Increment number of failed operations. */ public synchronized void incrementFailedOps() { ++numFailedOps; } /** * Update Latency. */ public synchronized void updateLatency(long latency) { if (latency < 0) { // less than 0ms . Ideally this should not happen. // We have seen this latency negative in some cases due to the // behaviors of JVM. Ignoring the statistics updation for such // cases. LOG.warn("Latency time coming negative"); return; } totalLatency += latency; ++numSuccessOps; if (latency < minLatency) { minLatency = latency; } if (latency > maxLatency) { maxLatency = latency; } int bucket; if (latency <= 100) { // less than 100ms bucket = (int) (latency / 10); } else if (latency <= 1000) { // 100ms ~ 1000ms bucket = 1 * 9 + (int) (latency / 100); } else if (latency <= 10000) { // 1s ~ 10s bucket = 2 * 9 + (int) (latency / 1000); } else { // more than 10s bucket = 3 * 9 + 1; } ++latencyBuckets[bucket]; } public OpStatData toOpStatData() { double avgLatency = numSuccessOps > 0 ? totalLatency / numSuccessOps : 0.0f; StringBuilder sb = new StringBuilder(); for (int i = 0; i < NUM_BUCKETS; i++) { sb.append(latencyBuckets[i]); if (i != NUM_BUCKETS - 1) { sb.append(','); } } return new OpStatData(maxLatency, minLatency, avgLatency, numSuccessOps, numFailedOps, sb.toString()); } /** * Diff with base opstats. * * @param base * base opstats * @return diff opstats */ public OpStats diff(OpStats base) { OpStats diff = new OpStats(); diff.maxLatency = this.maxLatency > base.maxLatency ? this.maxLatency : base.maxLatency; diff.minLatency = this.minLatency > base.minLatency ? base.minLatency : this.minLatency; diff.totalLatency = this.totalLatency - base.totalLatency; diff.numSuccessOps = this.numSuccessOps - base.numSuccessOps; diff.numFailedOps = this.numFailedOps - base.numFailedOps; for (int i = 0; i < NUM_BUCKETS; i++) { diff.latencyBuckets[i] = this.latencyBuckets[i] - base.latencyBuckets[i]; } return diff; } /** * Copy stats from other OpStats. * * @param other other op stats */ public synchronized void copyOf(OpStats other) { this.maxLatency = other.maxLatency; this.minLatency = other.minLatency; this.totalLatency = other.totalLatency; this.numSuccessOps = other.numSuccessOps; this.numFailedOps = other.numFailedOps; System.arraycopy(other.latencyBuckets, 0, this.latencyBuckets, 0, this.latencyBuckets.length); } } public static final int STATS_ADD = 0; public static final int STATS_READ = 1; public static final int STATS_UNKNOWN = 2; // NOTE: if add other stats, increment NUM_STATS public static final int NUM_STATS = 3; OpStats[] stats = new OpStats[NUM_STATS]; private BKStats() { for (int i = 0; i < NUM_STATS; i++) { stats[i] = new OpStats(); } } /** * Stats of operations. * * @return op stats */ public OpStats getOpStats(int type) { return stats[type]; } /** * Set stats of a specified operation. * * @param type operation type * @param stat operation stats */ public void setOpStats(int type, OpStats stat) { stats[type] = stat; } /** * Diff with base stats. * * @param base base stats * @return diff stats */ public BKStats diff(BKStats base) { BKStats diff = new BKStats(); for (int i = 0; i < NUM_STATS; i++) { diff.setOpStats(i, stats[i].diff(base.getOpStats(i))); } return diff; } /** * Copy stats from other stats. * * @param other other stats */ public void copyOf(BKStats other) { for (int i = 0; i < NUM_STATS; i++) { stats[i].copyOf(other.getOpStats(i)); } } }
77
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ReadEntryProcessor.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.proto; import io.netty.buffer.ByteBuf; import io.netty.util.Recycler; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.common.concurrent.FutureEventListener; import org.apache.bookkeeper.proto.BookieProtocol.ReadRequest; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class ReadEntryProcessor extends PacketProcessorBase<ReadRequest> { private static final Logger LOG = LoggerFactory.getLogger(ReadEntryProcessor.class); private ExecutorService fenceThreadPool; private boolean throttleReadResponses; public static ReadEntryProcessor create(ReadRequest request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor, ExecutorService fenceThreadPool, boolean throttleReadResponses) { ReadEntryProcessor rep = RECYCLER.get(); rep.init(request, requestHandler, requestProcessor); rep.fenceThreadPool = fenceThreadPool; rep.throttleReadResponses = throttleReadResponses; requestProcessor.onReadRequestStart(requestHandler.ctx().channel()); return rep; } @Override protected void processPacket() { if (LOG.isDebugEnabled()) { LOG.debug("Received new read request: {}", request); } if (!requestHandler.ctx().channel().isOpen()) { if (LOG.isDebugEnabled()) { LOG.debug("Dropping read request for closed channel: {}", requestHandler.ctx().channel()); } requestProcessor.onReadRequestFinish(); recycle(); return; } int errorCode = BookieProtocol.EOK; long startTimeNanos = MathUtils.nowInNano(); ByteBuf data = null; try { CompletableFuture<Boolean> fenceResult = null; if (request.isFencing()) { LOG.warn("Ledger: {} fenced by: {}", request.getLedgerId(), requestHandler.ctx().channel().remoteAddress()); if (request.hasMasterKey()) { fenceResult = requestProcessor.getBookie().fenceLedger(request.getLedgerId(), request.getMasterKey()); } else { LOG.error("Password not provided, Not safe to fence {}", request.getLedgerId()); throw BookieException.create(BookieException.Code.UnauthorizedAccessException); } } data = requestProcessor.getBookie().readEntry(request.getLedgerId(), request.getEntryId()); if (LOG.isDebugEnabled()) { LOG.debug("##### Read entry ##### {} -- ref-count: {}", data.readableBytes(), data.refCnt()); } if (fenceResult != null) { handleReadResultForFenceRead(fenceResult, data, startTimeNanos); return; } } catch (Bookie.NoLedgerException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error reading {}", request, e); } errorCode = BookieProtocol.ENOLEDGER; } catch (Bookie.NoEntryException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error reading {}", request, e); } errorCode = BookieProtocol.ENOENTRY; } catch (IOException e) { if (LOG.isDebugEnabled()) { LOG.debug("Error reading {}", request, e); } errorCode = BookieProtocol.EIO; } catch (BookieException.DataUnknownException e) { LOG.error("Ledger {} is in an unknown state", request.getLedgerId(), e); errorCode = BookieProtocol.EUNKNOWNLEDGERSTATE; } catch (BookieException e) { LOG.error("Unauthorized access to ledger {}", request.getLedgerId(), e); errorCode = BookieProtocol.EUA; } catch (Throwable t) { LOG.error("Unexpected exception reading at {}:{} : {}", request.getLedgerId(), request.getEntryId(), t.getMessage(), t); errorCode = BookieProtocol.EBADREQ; } if (LOG.isTraceEnabled()) { LOG.trace("Read entry rc = {} for {}", errorCode, request); } sendResponse(data, errorCode, startTimeNanos); } private void sendResponse(ByteBuf data, int errorCode, long startTimeNanos) { final RequestStats stats = requestProcessor.getRequestStats(); final OpStatsLogger logger = stats.getReadEntryStats(); BookieProtocol.Response response; if (errorCode == BookieProtocol.EOK) { logger.registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); response = ResponseBuilder.buildReadResponse(data, request); } else { if (data != null) { ReferenceCountUtil.release(data); } logger.registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); response = ResponseBuilder.buildErrorResponse(errorCode, request); } sendReadReqResponse(errorCode, response, stats.getReadRequestStats(), throttleReadResponses); recycle(); } private void sendFenceResponse(Boolean result, ByteBuf data, long startTimeNanos) { final int retCode = result != null && result ? BookieProtocol.EOK : BookieProtocol.EIO; sendResponse(data, retCode, startTimeNanos); } private void handleReadResultForFenceRead(CompletableFuture<Boolean> fenceResult, ByteBuf data, long startTimeNanos) { if (null != fenceThreadPool) { fenceResult.whenCompleteAsync(new FutureEventListener<Boolean>() { @Override public void onSuccess(Boolean result) { sendFenceResponse(result, data, startTimeNanos); } @Override public void onFailure(Throwable t) { LOG.error("Error processing fence request", t); // if failed to fence, fail the read request to make it retry. sendResponse(data, BookieProtocol.EIO, startTimeNanos); } }, fenceThreadPool); } else { try { Boolean fenced = fenceResult.get(1000, TimeUnit.MILLISECONDS); sendFenceResponse(fenced, data, startTimeNanos); return; } catch (InterruptedException ie) { Thread.currentThread().interrupt(); LOG.error("Interrupting fence read entry {}", request, ie); } catch (ExecutionException ee) { LOG.error("Failed to fence read entry {}", request, ee.getCause()); } catch (TimeoutException te) { LOG.error("Timeout to fence read entry {}", request, te); } sendResponse(data, BookieProtocol.EIO, startTimeNanos); } } @Override public String toString() { return String.format("ReadEntry(%d, %d)", request.getLedgerId(), request.getEntryId()); } void recycle() { request.recycle(); super.reset(); this.recyclerHandle.recycle(this); } private final Recycler.Handle<ReadEntryProcessor> recyclerHandle; private ReadEntryProcessor(Recycler.Handle<ReadEntryProcessor> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ReadEntryProcessor> RECYCLER = new Recycler<ReadEntryProcessor>() { @Override protected ReadEntryProcessor newObject(Recycler.Handle<ReadEntryProcessor> handle) { return new ReadEntryProcessor(handle); } }; }
78
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PacketProcessorBaseV3.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.proto; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; import org.apache.bookkeeper.proto.BookkeeperProtocol.BKPacketHeader; import org.apache.bookkeeper.proto.BookkeeperProtocol.ProtocolVersion; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.util.StringUtils; /** * A base class for bookkeeper protocol v3 packet processors. */ @Slf4j public abstract class PacketProcessorBaseV3 implements Runnable { final Request request; final BookieRequestHandler requestHandler; final BookieRequestProcessor requestProcessor; final long enqueueNanos; public PacketProcessorBaseV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { this.request = request; this.requestHandler = requestHandler; this.requestProcessor = requestProcessor; this.enqueueNanos = MathUtils.nowInNano(); } protected void sendResponse(StatusCode code, Object response, OpStatsLogger statsLogger) { final long writeNanos = MathUtils.nowInNano(); Channel channel = requestHandler.ctx().channel(); final long timeOut = requestProcessor.getWaitTimeoutOnBackpressureMillis(); if (timeOut >= 0 && !channel.isWritable()) { if (!requestProcessor.isBlacklisted(channel)) { synchronized (channel) { if (!channel.isWritable() && !requestProcessor.isBlacklisted(channel)) { final long waitUntilNanos = writeNanos + TimeUnit.MILLISECONDS.toNanos(timeOut); while (!channel.isWritable() && MathUtils.nowInNano() < waitUntilNanos) { try { TimeUnit.MILLISECONDS.sleep(1); } catch (InterruptedException e) { break; } } if (!channel.isWritable()) { requestProcessor.blacklistChannel(channel); requestProcessor.handleNonWritableChannel(channel); } } } } if (!channel.isWritable()) { log.warn("cannot write response to non-writable channel {} for request {}", channel, StringUtils.requestToString(request)); requestProcessor.getRequestStats().getChannelWriteStats() .registerFailedEvent(MathUtils.elapsedNanos(writeNanos), TimeUnit.NANOSECONDS); statsLogger.registerFailedEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); return; } else { requestProcessor.invalidateBlacklist(channel); } } if (channel.isActive()) { channel.writeAndFlush(response).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { long writeElapsedNanos = MathUtils.elapsedNanos(writeNanos); if (!future.isSuccess()) { requestProcessor.getRequestStats().getChannelWriteStats() .registerFailedEvent(writeElapsedNanos, TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getChannelWriteStats() .registerSuccessfulEvent(writeElapsedNanos, TimeUnit.NANOSECONDS); } if (StatusCode.EOK == code) { statsLogger.registerSuccessfulEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); } else { statsLogger.registerFailedEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); } } }); } else { log.debug("Netty channel {} is inactive, " + "hence bypassing netty channel writeAndFlush during sendResponse", channel); } } protected boolean isVersionCompatible() { return this.request.getHeader().getVersion().equals(ProtocolVersion.VERSION_THREE); } /** * Build a header with protocol version 3 and the operation type same as what was in the * request. * @return */ protected BKPacketHeader getHeader() { BKPacketHeader.Builder header = BKPacketHeader.newBuilder(); header.setVersion(ProtocolVersion.VERSION_THREE); header.setOperation(request.getHeader().getOperation()); header.setTxnId(request.getHeader().getTxnId()); return header.build(); } @Override public String toString() { return request.toString(); } }
79
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ReadLacProcessorV3.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.proto; import com.google.protobuf.ByteString; import io.netty.buffer.ByteBuf; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadLacRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadLacResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A read processor for v3 last add confirmed messages. */ class ReadLacProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ReadLacProcessorV3.class); public ReadLacProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); } // Returns null if there is no exception thrown private ReadLacResponse getReadLacResponse() { final long startTimeNanos = MathUtils.nowInNano(); ReadLacRequest readLacRequest = request.getReadLacRequest(); long ledgerId = readLacRequest.getLedgerId(); final ReadLacResponse.Builder readLacResponse = ReadLacResponse.newBuilder().setLedgerId(ledgerId); if (!isVersionCompatible()) { readLacResponse.setStatus(StatusCode.EBADVERSION); return readLacResponse.build(); } logger.debug("Received ReadLac request: {}", request); StatusCode status = StatusCode.EOK; ByteBuf lastEntry = null; ByteBuf lac = null; try { lac = requestProcessor.bookie.getExplicitLac(ledgerId); if (lac != null) { readLacResponse.setLacBody(ByteString.copyFrom(lac.nioBuffer())); } } catch (Bookie.NoLedgerException e) { status = StatusCode.ENOLEDGER; logger.debug("No ledger found while performing readLac from ledger: {}", ledgerId, e); } catch (BookieException.DataUnknownException e) { status = StatusCode.EUNKNOWNLEDGERSTATE; logger.error("Ledger {} in unknown state and cannot serve reacLac requests", ledgerId, e); } catch (BookieException | IOException e) { status = StatusCode.EIO; logger.error("IOException while performing readLac from ledger: {}", ledgerId, e); } finally { ReferenceCountUtil.release(lac); } try { lastEntry = requestProcessor.bookie.readEntry(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED); if (lastEntry != null) { readLacResponse.setLastEntryBody(ByteString.copyFrom(lastEntry.nioBuffer())); } } catch (Bookie.NoLedgerException e) { status = StatusCode.ENOLEDGER; logger.debug("No ledger found while trying to read last entry: {}", ledgerId, e); } catch (BookieException.DataUnknownException e) { status = StatusCode.EUNKNOWNLEDGERSTATE; logger.error("Ledger in an unknown state while trying to read last entry: {}", ledgerId, e); } catch (BookieException | IOException e) { status = StatusCode.EIO; logger.error("IOException while trying to read last entry: {}", ledgerId, e); } finally { ReferenceCountUtil.release(lastEntry); } if ((lac == null) && (lastEntry == null)) { status = StatusCode.ENOENTRY; } if (status == StatusCode.EOK) { requestProcessor.getRequestStats().getReadLacStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getReadLacStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } // Finally set the status and return readLacResponse.setStatus(status); return readLacResponse.build(); } @Override public void run() { ReadLacResponse readLacResponse = getReadLacResponse(); sendResponse(readLacResponse); } private void sendResponse(ReadLacResponse readLacResponse) { Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(readLacResponse.getStatus()) .setReadLacResponse(readLacResponse); sendResponse(response.getStatus(), response.build(), requestProcessor.getRequestStats().getReadLacRequestStats()); } }
80
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/GetBookieInfoProcessorV3.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.proto; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetBookieInfoRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.GetBookieInfoResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A processor class for v3 bookie metadata packets. */ public class GetBookieInfoProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(GetBookieInfoProcessorV3.class); public GetBookieInfoProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); } private GetBookieInfoResponse getGetBookieInfoResponse() { long startTimeNanos = MathUtils.nowInNano(); GetBookieInfoRequest getBookieInfoRequest = request.getGetBookieInfoRequest(); long requested = getBookieInfoRequest.getRequested(); GetBookieInfoResponse.Builder getBookieInfoResponse = GetBookieInfoResponse.newBuilder(); if (!isVersionCompatible()) { getBookieInfoResponse.setStatus(StatusCode.EBADVERSION); requestProcessor.getRequestStats().getGetBookieInfoStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); return getBookieInfoResponse.build(); } if (LOG.isDebugEnabled()) { LOG.debug("Received new getBookieInfo request: {}", request); } StatusCode status = StatusCode.EOK; long freeDiskSpace = 0L, totalDiskSpace = 0L; try { if ((requested & GetBookieInfoRequest.Flags.FREE_DISK_SPACE_VALUE) != 0) { freeDiskSpace = requestProcessor.getBookie().getTotalFreeSpace(); getBookieInfoResponse.setFreeDiskSpace(freeDiskSpace); } if ((requested & GetBookieInfoRequest.Flags.TOTAL_DISK_CAPACITY_VALUE) != 0) { totalDiskSpace = requestProcessor.getBookie().getTotalDiskSpace(); getBookieInfoResponse.setTotalDiskCapacity(totalDiskSpace); } if (LOG.isDebugEnabled()) { LOG.debug("FreeDiskSpace info is " + freeDiskSpace + " totalDiskSpace is: " + totalDiskSpace); } requestProcessor.getRequestStats().getGetBookieInfoStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } catch (IOException e) { status = StatusCode.EIO; LOG.error("IOException while getting freespace/totalspace", e); requestProcessor.getRequestStats().getGetBookieInfoStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } getBookieInfoResponse.setStatus(status); return getBookieInfoResponse.build(); } @Override public void run() { GetBookieInfoResponse getBookieInfoResponse = getGetBookieInfoResponse(); sendResponse(getBookieInfoResponse); } private void sendResponse(GetBookieInfoResponse getBookieInfoResponse) { Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(getBookieInfoResponse.getStatus()) .setGetBookieInfoResponse(getBookieInfoResponse); sendResponse(response.getStatus(), response.build(), requestProcessor.getRequestStats().getGetBookieInfoRequestStats()); } }
81
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieClientImpl.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.proto; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.Lists; import com.google.protobuf.ExtensionRegistry; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.util.EnumSet; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.bookkeeper.auth.AuthProviderFactoryFactory; import org.apache.bookkeeper.auth.ClientAuthProvider; import org.apache.bookkeeper.client.BKException; import org.apache.bookkeeper.client.BookieInfoReader.BookieInfo; import org.apache.bookkeeper.client.api.WriteFlag; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.conf.ClientConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ForceLedgerCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.FutureGetListOfEntriesOfLedger; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GetBookieInfoCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadLacCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteLacCallback; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.tls.SecurityException; import org.apache.bookkeeper.tls.SecurityHandlerFactory; import org.apache.bookkeeper.util.AvailabilityOfEntriesOfLedger; import org.apache.bookkeeper.util.ByteBufList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements the client-side part of the BookKeeper protocol. * */ public class BookieClientImpl implements BookieClient, PerChannelBookieClientFactory { static final Logger LOG = LoggerFactory.getLogger(BookieClientImpl.class); private final OrderedExecutor executor; private final ScheduledExecutorService scheduler; private final ScheduledFuture<?> timeoutFuture; private final EventLoopGroup eventLoopGroup; private final ByteBufAllocator allocator; final ConcurrentHashMap<BookieId, PerChannelBookieClientPool> channels = new ConcurrentHashMap<BookieId, PerChannelBookieClientPool>(); private final ClientAuthProvider.Factory authProviderFactory; private final ExtensionRegistry registry; private final ClientConfiguration conf; private final ClientConfiguration v3Conf; private final boolean useV3Enforced; private volatile boolean closed; private final ReentrantReadWriteLock closeLock; private final StatsLogger statsLogger; private final int numConnectionsPerBookie; private final BookieAddressResolver bookieAddressResolver; private final long bookieErrorThresholdPerInterval; public BookieClientImpl(ClientConfiguration conf, EventLoopGroup eventLoopGroup, ByteBufAllocator allocator, OrderedExecutor executor, ScheduledExecutorService scheduler, StatsLogger statsLogger, BookieAddressResolver bookieAddressResolver) throws IOException { this.conf = conf; this.v3Conf = new ClientConfiguration(conf); this.v3Conf.setUseV2WireProtocol(false); this.useV3Enforced = conf.getUseV2WireProtocol(); this.eventLoopGroup = eventLoopGroup; this.allocator = allocator; this.executor = executor; this.closed = false; this.closeLock = new ReentrantReadWriteLock(); this.bookieAddressResolver = bookieAddressResolver; this.registry = ExtensionRegistry.newInstance(); this.authProviderFactory = AuthProviderFactoryFactory.newClientAuthProviderFactory(conf); this.statsLogger = statsLogger; this.numConnectionsPerBookie = conf.getNumChannelsPerBookie(); this.bookieErrorThresholdPerInterval = conf.getBookieErrorThresholdPerInterval(); this.scheduler = scheduler; if (conf.getAddEntryTimeout() > 0 || conf.getReadEntryTimeout() > 0) { this.timeoutFuture = this.scheduler.scheduleAtFixedRate( () -> monitorPendingOperations(), conf.getTimeoutMonitorIntervalSec(), conf.getTimeoutMonitorIntervalSec(), TimeUnit.SECONDS); } else { this.timeoutFuture = null; } } private int getRc(int rc) { if (BKException.Code.OK == rc) { return rc; } else { if (closed) { return BKException.Code.ClientClosedException; } else { return rc; } } } @Override public List<BookieId> getFaultyBookies() { List<BookieId> faultyBookies = Lists.newArrayList(); for (PerChannelBookieClientPool channelPool : channels.values()) { if (channelPool instanceof DefaultPerChannelBookieClientPool) { DefaultPerChannelBookieClientPool pool = (DefaultPerChannelBookieClientPool) channelPool; if (pool.errorCounter.getAndSet(0) >= bookieErrorThresholdPerInterval) { faultyBookies.add(pool.address); } } } return faultyBookies; } @Override public boolean isWritable(BookieId address, long key) { final PerChannelBookieClientPool pcbcPool = lookupClient(address); // if null, let the write initiate connect of fail with whatever error it produces return pcbcPool == null || pcbcPool.isWritable(key); } @Override public long getNumPendingRequests(BookieId address, long ledgerId) { PerChannelBookieClientPool pcbcPool = lookupClient(address); if (pcbcPool == null) { return 0; } else if (pcbcPool.isWritable(ledgerId)) { return pcbcPool.getNumPendingCompletionRequests(); } else { return pcbcPool.getNumPendingCompletionRequests() | PENDINGREQ_NOTWRITABLE_MASK; } } @Override public PerChannelBookieClient create(BookieId address, PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory, boolean forceUseV3) throws SecurityException { StatsLogger statsLoggerForPCBC = statsLogger; if (conf.getLimitStatsLogging()) { statsLoggerForPCBC = NullStatsLogger.INSTANCE; } ClientConfiguration clientConfiguration = conf; if (forceUseV3) { clientConfiguration = v3Conf; } return new PerChannelBookieClient(clientConfiguration, executor, eventLoopGroup, allocator, address, statsLoggerForPCBC, authProviderFactory, registry, pcbcPool, shFactory, bookieAddressResolver); } public PerChannelBookieClientPool lookupClient(BookieId addr) { PerChannelBookieClientPool clientPool = channels.get(addr); if (null == clientPool) { closeLock.readLock().lock(); try { if (closed) { return null; } PerChannelBookieClientPool newClientPool = new DefaultPerChannelBookieClientPool(conf, this, addr, numConnectionsPerBookie); PerChannelBookieClientPool oldClientPool = channels.putIfAbsent(addr, newClientPool); if (null == oldClientPool) { clientPool = newClientPool; // initialize the pool only after we put the pool into the map clientPool.initialize(); } else { clientPool = oldClientPool; newClientPool.close(false); } } catch (SecurityException e) { LOG.error("Security Exception in creating new default PCBC pool: ", e); return null; } finally { closeLock.readLock().unlock(); } } return clientPool; } @Override public void forceLedger(final BookieId addr, final long ledgerId, final ForceLedgerCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.forceLedgerComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, () -> cb.forceLedgerComplete(rc, ledgerId, addr, ctx)); } catch (RejectedExecutionException re) { cb.forceLedgerComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.forceLedger(ledgerId, cb, ctx); } }, ledgerId); } @Override public void writeLac(final BookieId addr, final long ledgerId, final byte[] masterKey, final long lac, final ByteBufList toSend, final WriteLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.writeLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, addr, ctx); return; } toSend.retain(); client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, () -> cb.writeLacComplete(rc, ledgerId, addr, ctx)); } catch (RejectedExecutionException re) { cb.writeLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, addr, ctx); } } else { pcbc.writeLac(ledgerId, masterKey, lac, toSend, cb, ctx); } ReferenceCountUtil.release(toSend); }, ledgerId, useV3Enforced); } private void completeAdd(final int rc, final long ledgerId, final long entryId, final BookieId addr, final WriteCallback cb, final Object ctx) { cb.writeComplete(rc, ledgerId, entryId, addr, ctx); } @Override public void addEntry(final BookieId addr, final long ledgerId, final byte[] masterKey, final long entryId, final ReferenceCounted toSend, final WriteCallback cb, final Object ctx, final int options, final boolean allowFastFail, final EnumSet<WriteFlag> writeFlags) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { completeAdd(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, entryId, addr, cb, ctx); return; } // Retain the buffer, since the connection could be obtained after // the PendingApp might have already failed toSend.retain(); client.obtain(ChannelReadyForAddEntryCallback.create( this, toSend, ledgerId, entryId, addr, ctx, cb, options, masterKey, allowFastFail, writeFlags), ledgerId); } @Override public CompletableFuture<AvailabilityOfEntriesOfLedger> getListOfEntriesOfLedger(BookieId address, long ledgerId) { FutureGetListOfEntriesOfLedger futureResult = new FutureGetListOfEntriesOfLedger(ledgerId); final PerChannelBookieClientPool client = lookupClient(address); if (client == null) { futureResult.getListOfEntriesOfLedgerComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, null); return futureResult; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, () -> futureResult.getListOfEntriesOfLedgerComplete(rc, ledgerId, null) ); } catch (RejectedExecutionException re) { futureResult.getListOfEntriesOfLedgerComplete(getRc(BKException.Code.InterruptedException), ledgerId, null); } } else { pcbc.getListOfEntriesOfLedger(ledgerId, futureResult); } }, ledgerId); return futureResult; } private void completeRead(final int rc, final long ledgerId, final long entryId, final ByteBuf entry, final ReadEntryCallback cb, final Object ctx) { try { executor.executeOrdered(ledgerId, () -> cb.readEntryComplete(rc, ledgerId, entryId, entry, ctx)); } catch (RejectedExecutionException ree) { cb.readEntryComplete(getRc(BKException.Code.InterruptedException), ledgerId, entryId, entry, ctx); } } private static class ChannelReadyForAddEntryCallback implements GenericCallback<PerChannelBookieClient> { private final Handle<ChannelReadyForAddEntryCallback> recyclerHandle; private BookieClientImpl bookieClient; private ReferenceCounted toSend; private long ledgerId; private long entryId; private BookieId addr; private Object ctx; private WriteCallback cb; private int options; private byte[] masterKey; private boolean allowFastFail; private EnumSet<WriteFlag> writeFlags; static ChannelReadyForAddEntryCallback create( BookieClientImpl bookieClient, ReferenceCounted toSend, long ledgerId, long entryId, BookieId addr, Object ctx, WriteCallback cb, int options, byte[] masterKey, boolean allowFastFail, EnumSet<WriteFlag> writeFlags) { ChannelReadyForAddEntryCallback callback = RECYCLER.get(); callback.bookieClient = bookieClient; callback.toSend = toSend; callback.ledgerId = ledgerId; callback.entryId = entryId; callback.addr = addr; callback.ctx = ctx; callback.cb = cb; callback.options = options; callback.masterKey = masterKey; callback.allowFastFail = allowFastFail; callback.writeFlags = writeFlags; return callback; } @Override public void operationComplete(final int rc, PerChannelBookieClient pcbc) { if (rc != BKException.Code.OK) { bookieClient.completeAdd(rc, ledgerId, entryId, addr, cb, ctx); } else { pcbc.addEntry(ledgerId, masterKey, entryId, toSend, cb, ctx, options, allowFastFail, writeFlags); } ReferenceCountUtil.release(toSend); recycle(); } private ChannelReadyForAddEntryCallback( Handle<ChannelReadyForAddEntryCallback> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ChannelReadyForAddEntryCallback> RECYCLER = new Recycler<ChannelReadyForAddEntryCallback>() { @Override protected ChannelReadyForAddEntryCallback newObject( Recycler.Handle<ChannelReadyForAddEntryCallback> recyclerHandle) { return new ChannelReadyForAddEntryCallback(recyclerHandle); } }; public void recycle() { bookieClient = null; toSend = null; ledgerId = -1; entryId = -1; addr = null; ctx = null; cb = null; options = -1; masterKey = null; allowFastFail = false; writeFlags = null; recyclerHandle.recycle(this); } } @Override public void readLac(final BookieId addr, final long ledgerId, final ReadLacCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.readLacComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, null, null, ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.executeOrdered(ledgerId, () -> cb.readLacComplete(rc, ledgerId, null, null, ctx)); } catch (RejectedExecutionException re) { cb.readLacComplete(getRc(BKException.Code.InterruptedException), ledgerId, null, null, ctx); } } else { pcbc.readLac(ledgerId, cb, ctx); } }, ledgerId, useV3Enforced); } @Override public void readEntry(BookieId addr, long ledgerId, long entryId, ReadEntryCallback cb, Object ctx, int flags) { readEntry(addr, ledgerId, entryId, cb, ctx, flags, null); } @Override public void readEntry(final BookieId addr, final long ledgerId, final long entryId, final ReadEntryCallback cb, final Object ctx, int flags, byte[] masterKey) { readEntry(addr, ledgerId, entryId, cb, ctx, flags, masterKey, false); } @Override public void readEntry(final BookieId addr, final long ledgerId, final long entryId, final ReadEntryCallback cb, final Object ctx, int flags, byte[] masterKey, final boolean allowFastFail) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.readEntryComplete(getRc(BKException.Code.BookieHandleNotAvailableException), ledgerId, entryId, null, ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { completeRead(rc, ledgerId, entryId, null, cb, ctx); } else { pcbc.readEntry(ledgerId, entryId, cb, ctx, flags, masterKey, allowFastFail); } }, ledgerId); } @Override public void readEntryWaitForLACUpdate(final BookieId addr, final long ledgerId, final long entryId, final long previousLAC, final long timeOutInMillis, final boolean piggyBackEntry, final ReadEntryCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { completeRead(BKException.Code.BookieHandleNotAvailableException, ledgerId, entryId, null, cb, ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { completeRead(rc, ledgerId, entryId, null, cb, ctx); } else { pcbc.readEntryWaitForLACUpdate(ledgerId, entryId, previousLAC, timeOutInMillis, piggyBackEntry, cb, ctx); } }, ledgerId); } @Override public void getBookieInfo(final BookieId addr, final long requested, final GetBookieInfoCallback cb, final Object ctx) { final PerChannelBookieClientPool client = lookupClient(addr); if (client == null) { cb.getBookieInfoComplete(getRc(BKException.Code.BookieHandleNotAvailableException), new BookieInfo(), ctx); return; } client.obtain((rc, pcbc) -> { if (rc != BKException.Code.OK) { try { executor.execute(() -> cb.getBookieInfoComplete(rc, new BookieInfo(), ctx)); } catch (RejectedExecutionException re) { cb.getBookieInfoComplete(getRc(BKException.Code.InterruptedException), new BookieInfo(), ctx); } } else { pcbc.getBookieInfo(requested, cb, ctx); } }, requested, useV3Enforced); } private void monitorPendingOperations() { for (PerChannelBookieClientPool clientPool : channels.values()) { clientPool.checkTimeoutOnPendingOperations(); } } @Override public boolean isClosed() { return closed; } @Override public void close() { closeLock.writeLock().lock(); try { closed = true; for (PerChannelBookieClientPool pool : channels.values()) { pool.close(true); } channels.clear(); authProviderFactory.close(); if (timeoutFuture != null) { timeoutFuture.cancel(false); } } finally { closeLock.writeLock().unlock(); } } private static class Counter { int i; int total; synchronized void inc() { i++; total++; } synchronized void dec() { i--; notifyAll(); } synchronized void wait(int limit) throws InterruptedException { while (i > limit) { wait(); } } synchronized int total() { return total; } } /** * @param args * @throws IOException * @throws NumberFormatException * @throws InterruptedException */ public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException { if (args.length != 3) { System.err.println("USAGE: BookieClient bookieHost port ledger#"); return; } WriteCallback cb = new WriteCallback() { @Override public void writeComplete(int rc, long ledger, long entry, BookieId addr, Object ctx) { Counter counter = (Counter) ctx; counter.dec(); if (rc != 0) { System.out.println("rc = " + rc + " for " + entry + "@" + ledger); } } }; Counter counter = new Counter(); byte[] hello = "hello".getBytes(UTF_8); long ledger = Long.parseLong(args[2]); EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1); OrderedExecutor executor = OrderedExecutor.newBuilder() .name("BookieClientWorker") .numThreads(1) .build(); ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor( new DefaultThreadFactory("BookKeeperClientScheduler")); BookieClientImpl bc = new BookieClientImpl(new ClientConfiguration(), eventLoopGroup, null, executor, scheduler, NullStatsLogger.INSTANCE, BookieSocketAddress.LEGACY_BOOKIEID_RESOLVER); BookieId addr = new BookieSocketAddress(args[0], Integer.parseInt(args[1])).toBookieId(); for (int i = 0; i < 100000; i++) { counter.inc(); bc.addEntry(addr, ledger, new byte[0], i, ByteBufList.get(Unpooled.wrappedBuffer(hello)), cb, counter, 0, false, WriteFlag.NONE); } counter.wait(0); System.out.println("Total = " + counter.total()); scheduler.shutdown(); eventLoopGroup.shutdownGracefully(); executor.shutdown(); } }
82
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieNettyServer.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.proto; import com.google.common.annotations.VisibleForTesting; import com.google.protobuf.ExtensionRegistry; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.PooledByteBufAllocator; import io.netty.channel.AdaptiveRecvByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandler; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; import io.netty.channel.ChannelPipeline; import io.netty.channel.DefaultEventLoop; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.WriteBufferWaterMark; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollServerSocketChannel; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.ChannelGroupFuture; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.flush.FlushConsolidationHandler; import io.netty.handler.ssl.SslHandler; import io.netty.incubator.channel.uring.IOUringEventLoopGroup; import io.netty.incubator.channel.uring.IOUringServerSocketChannel; import io.netty.util.concurrent.DefaultThreadFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.security.cert.Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.bookkeeper.auth.AuthProviderFactoryFactory; import org.apache.bookkeeper.auth.BookKeeperPrincipal; import org.apache.bookkeeper.auth.BookieAuthProvider; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.common.collections.BlockingMpscQueue; import org.apache.bookkeeper.common.util.affinity.CpuAffinity; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.processor.RequestProcessor; import org.apache.bookkeeper.util.ByteBufList; import org.apache.bookkeeper.util.EventLoopUtil; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Netty server for serving bookie requests. */ class BookieNettyServer { private static final Logger LOG = LoggerFactory.getLogger(BookieNettyServer.class); final int maxFrameSize; final ServerConfiguration conf; final EventLoopGroup eventLoopGroup; final EventLoopGroup acceptorGroup; final EventLoopGroup jvmEventLoopGroup; RequestProcessor requestProcessor; final AtomicBoolean isRunning = new AtomicBoolean(false); final AtomicBoolean isClosed = new AtomicBoolean(false); final Object suspensionLock = new Object(); volatile boolean suspended = false; ChannelGroup allChannels; final BookieSocketAddress bookieAddress; final BookieId bookieId; final InetSocketAddress bindAddress; final BookieAuthProvider.Factory authProviderFactory; final ExtensionRegistry registry = ExtensionRegistry.newInstance(); private final ByteBufAllocator allocator; BookieNettyServer(ServerConfiguration conf, RequestProcessor processor, ByteBufAllocator allocator) throws IOException, KeeperException, InterruptedException, BookieException { this.allocator = allocator; this.maxFrameSize = conf.getNettyMaxFrameSizeBytes(); this.conf = conf; this.requestProcessor = processor; this.authProviderFactory = AuthProviderFactoryFactory.newBookieAuthProviderFactory(conf); if (!conf.isDisableServerSocketBind()) { this.eventLoopGroup = EventLoopUtil.getServerEventLoopGroup(conf, new DefaultThreadFactory("bookie-io")); this.acceptorGroup = EventLoopUtil.getServerAcceptorGroup(conf, new DefaultThreadFactory("bookie-acceptor")); allChannels = new CleanupChannelGroup(eventLoopGroup); } else { this.eventLoopGroup = null; this.acceptorGroup = null; } if (conf.isEnableLocalTransport()) { jvmEventLoopGroup = new DefaultEventLoopGroup(conf.getServerNumIOThreads()) { @Override protected EventLoop newChild(Executor executor, Object... args) throws Exception { return new DefaultEventLoop(this, executor) { @Override protected Queue<Runnable> newTaskQueue(int maxPendingTasks) { if (conf.isBusyWaitEnabled()) { return new BlockingMpscQueue<>(Math.min(maxPendingTasks, 10_000)); } else { return super.newTaskQueue(maxPendingTasks); } } }; } }; // Enable CPU affinity on IO threads if (conf.isBusyWaitEnabled()) { for (int i = 0; i < conf.getServerNumIOThreads(); i++) { jvmEventLoopGroup.next().submit(() -> { try { CpuAffinity.acquireCore(); } catch (Throwable t) { LOG.warn("Failed to acquire CPU core for thread {} {}", Thread.currentThread().getName(), t.getMessage(), t); } }); } } allChannels = new CleanupChannelGroup(jvmEventLoopGroup); } else { jvmEventLoopGroup = null; } bookieId = BookieImpl.getBookieId(conf); bookieAddress = BookieImpl.getBookieAddress(conf); if (conf.getListeningInterface() == null) { bindAddress = new InetSocketAddress(conf.getBookiePort()); } else { bindAddress = bookieAddress.getSocketAddress(); } listenOn(bindAddress, bookieAddress); } public BookieNettyServer setRequestProcessor(RequestProcessor processor) { this.requestProcessor = processor; return this; } boolean isRunning() { return isRunning.get(); } @VisibleForTesting void suspendProcessing() { synchronized (suspensionLock) { suspended = true; for (Channel channel : allChannels) { // To suspend processing in the bookie, submit a task // that keeps the event loop busy until resume is // explicitly invoked channel.eventLoop().submit(() -> { while (suspended && isRunning()) { try { Thread.sleep(10); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); } } } @VisibleForTesting void resumeProcessing() { synchronized (suspensionLock) { suspended = false; for (Channel channel : allChannels) { channel.config().setAutoRead(true); } suspensionLock.notifyAll(); } } class BookieSideConnectionPeerContextHandler extends ChannelInboundHandlerAdapter { final BookieConnectionPeer connectionPeer; volatile Channel channel; volatile BookKeeperPrincipal authorizedId = BookKeeperPrincipal.ANONYMOUS; public BookieSideConnectionPeerContextHandler() { this.connectionPeer = new BookieConnectionPeer() { @Override public SocketAddress getRemoteAddr() { Channel c = channel; if (c != null) { return c.remoteAddress(); } else { return null; } } @Override public Collection<Object> getProtocolPrincipals() { Channel c = channel; if (c == null) { return Collections.emptyList(); } else { SslHandler ssl = c.pipeline().get(SslHandler.class); if (ssl == null) { return Collections.emptyList(); } try { Certificate[] certificates = ssl.engine().getSession().getPeerCertificates(); if (certificates == null) { return Collections.emptyList(); } List<Object> result = new ArrayList<>(); result.addAll(Arrays.asList(certificates)); return result; } catch (SSLPeerUnverifiedException err) { LOG.error("Failed to get peer certificates", err); return Collections.emptyList(); } } } @Override public void disconnect() { Channel c = channel; if (c != null) { c.close(); } LOG.info("authplugin disconnected channel {}", channel); } @Override public BookKeeperPrincipal getAuthorizedId() { return authorizedId; } @Override public void setAuthorizedId(BookKeeperPrincipal principal) { LOG.info("connection {} authenticated as {}", channel, principal); authorizedId = principal; } @Override public boolean isSecure() { Channel c = channel; if (c == null) { return false; } else { return c.pipeline().get("tls") != null; } } }; } public BookieConnectionPeer getConnectionPeer() { return connectionPeer; } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { channel = ctx.channel(); } } private void listenOn(InetSocketAddress address, BookieSocketAddress bookieAddress) throws InterruptedException { if (!conf.isDisableServerSocketBind()) { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.option(ChannelOption.ALLOCATOR, allocator); bootstrap.childOption(ChannelOption.ALLOCATOR, allocator); bootstrap.group(acceptorGroup, eventLoopGroup); bootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); bootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); bootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (eventLoopGroup instanceof IOUringEventLoopGroup){ bootstrap.channel(IOUringServerSocketChannel.class); } else if (eventLoopGroup instanceof EpollEventLoopGroup) { bootstrap.channel(EpollServerSocketChannel.class); } else { bootstrap.channel(NioServerSocketChannel.class); } bootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("consolidation", new FlushConsolidationHandler(1024, true)); pipeline.addLast("bytebufList", ByteBufList.ENCODER); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); // Bind and start to accept incoming connections LOG.info("Binding bookie-rpc endpoint to {}", address); Channel listen = bootstrap.bind(address.getAddress(), address.getPort()).sync().channel(); if (listen.localAddress() instanceof InetSocketAddress) { if (conf.getBookiePort() == 0) { // this is really really nasty. It's using the configuration object as a notification // bus. We should get rid of this at some point conf.setBookiePort(((InetSocketAddress) listen.localAddress()).getPort()); } } } if (conf.isEnableLocalTransport()) { ServerBootstrap jvmBootstrap = new ServerBootstrap(); jvmBootstrap.childOption(ChannelOption.ALLOCATOR, new PooledByteBufAllocator(true)); jvmBootstrap.group(jvmEventLoopGroup, jvmEventLoopGroup); jvmBootstrap.childOption(ChannelOption.TCP_NODELAY, conf.getServerTcpNoDelay()); jvmBootstrap.childOption(ChannelOption.SO_KEEPALIVE, conf.getServerSockKeepalive()); jvmBootstrap.childOption(ChannelOption.SO_LINGER, conf.getServerSockLinger()); jvmBootstrap.childOption(ChannelOption.RCVBUF_ALLOCATOR, new AdaptiveRecvByteBufAllocator(conf.getRecvByteBufAllocatorSizeMin(), conf.getRecvByteBufAllocatorSizeInitial(), conf.getRecvByteBufAllocatorSizeMax())); jvmBootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, new WriteBufferWaterMark( conf.getServerWriteBufferLowWaterMark(), conf.getServerWriteBufferHighWaterMark())); if (jvmEventLoopGroup instanceof DefaultEventLoopGroup) { jvmBootstrap.channel(LocalServerChannel.class); } else if (jvmEventLoopGroup instanceof IOUringEventLoopGroup) { jvmBootstrap.channel(IOUringServerSocketChannel.class); } else if (jvmEventLoopGroup instanceof EpollEventLoopGroup) { jvmBootstrap.channel(EpollServerSocketChannel.class); } else { jvmBootstrap.channel(NioServerSocketChannel.class); } jvmBootstrap.childHandler(new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) throws Exception { synchronized (suspensionLock) { while (suspended) { suspensionLock.wait(); } } BookieSideConnectionPeerContextHandler contextHandler = new BookieSideConnectionPeerContextHandler(); ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(maxFrameSize, 0, 4, 0, 4)); pipeline.addLast("bookieProtoDecoder", new BookieProtoEncoding.RequestDecoder(registry)); pipeline.addLast("bookieProtoEncoder", new BookieProtoEncoding.ResponseEncoder(registry)); pipeline.addLast("bookieAuthHandler", new AuthHandler.ServerSideHandler( contextHandler.getConnectionPeer(), authProviderFactory)); ChannelInboundHandler requestHandler = isRunning.get() ? new BookieRequestHandler(conf, requestProcessor, allChannels) : new RejectRequestHandler(); pipeline.addLast("bookieRequestHandler", requestHandler); pipeline.addLast("contextHandler", contextHandler); } }); LOG.info("Binding jvm bookie-rpc endpoint to {}", bookieId.toString()); // use the same address 'name', so clients can find local Bookie still discovering them using ZK jvmBootstrap.bind(new LocalAddress(bookieId.toString())).sync(); LocalBookiesRegistry.registerLocalBookieAddress(bookieId); } } void start() throws InterruptedException { isRunning.set(true); } void shutdown() { LOG.info("Shutting down BookieNettyServer"); isRunning.set(false); if (!isClosed.compareAndSet(false, true)) { // the netty server is already closed. return; } allChannels.close().awaitUninterruptibly(); if (acceptorGroup != null) { try { acceptorGroup.shutdownGracefully(0, 10, TimeUnit.MILLISECONDS).await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (eventLoopGroup != null) { try { eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.MILLISECONDS).await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); /// OK } } if (jvmEventLoopGroup != null) { LocalBookiesRegistry.unregisterLocalBookieAddress(bookieAddress.toBookieId()); jvmEventLoopGroup.shutdownGracefully(); } authProviderFactory.close(); } private static class RejectRequestHandler extends ChannelInboundHandlerAdapter { @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { ctx.channel().close(); } } private static class CleanupChannelGroup extends DefaultChannelGroup { private AtomicBoolean closed = new AtomicBoolean(false); public CleanupChannelGroup(EventLoopGroup eventLoopGroup) { super("BookieChannelGroup", eventLoopGroup.next()); } @Override public boolean add(Channel channel) { boolean ret = super.add(channel); if (closed.get()) { channel.close(); } return ret; } @Override public ChannelGroupFuture close() { closed.set(true); return super.close(); } @Override public boolean equals(Object o) { if (!(o instanceof CleanupChannelGroup)) { return false; } CleanupChannelGroup other = (CleanupChannelGroup) o; return other.closed.get() == closed.get() && super.equals(other); } @Override public int hashCode() { return super.hashCode() * 17 + (closed.get() ? 1 : 0); } } }
83
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieRequestProcessor.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.proto; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.bookkeeper.proto.RequestUtils.hasFlag; import com.google.common.annotations.VisibleForTesting; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.protobuf.ByteString; import io.netty.buffer.ByteBufAllocator; import io.netty.channel.Channel; import io.netty.channel.group.ChannelGroup; import io.netty.handler.ssl.SslHandler; import io.netty.util.HashedWheelTimer; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import lombok.AccessLevel; import lombok.Getter; import org.apache.bookkeeper.auth.AuthProviderFactoryFactory; import org.apache.bookkeeper.auth.AuthToken; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.common.util.MathUtils; import org.apache.bookkeeper.common.util.OrderedExecutor; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.processor.RequestProcessor; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.tls.SecurityException; import org.apache.bookkeeper.tls.SecurityHandlerFactory; import org.apache.bookkeeper.tls.SecurityHandlerFactory.NodeType; import org.apache.bookkeeper.util.NettyChannelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; /** * An implementation of the RequestProcessor interface. */ @Getter(AccessLevel.PACKAGE) public class BookieRequestProcessor implements RequestProcessor { private static final Logger LOG = LoggerFactory.getLogger(BookieRequestProcessor.class); /** * The server configuration. We use this for getting the number of add and read * worker threads. */ private final ServerConfiguration serverCfg; private final long waitTimeoutOnBackpressureMillis; private final boolean preserveMdcForTaskExecution; /** * This is the Bookie instance that is used to handle all read and write requests. */ final Bookie bookie; /** * The threadpool used to execute all read entry requests issued to this server. */ private final OrderedExecutor readThreadPool; /** * The threadpool used to execute all add entry requests issued to this server. */ private final OrderedExecutor writeThreadPool; /** * TLS management. */ private final SecurityHandlerFactory shFactory; /** * The threadpool used to execute all long poll requests issued to this server * after they are done waiting. */ private final OrderedExecutor longPollThreadPool; /** * The threadpool used to execute high priority requests. */ private final OrderedExecutor highPriorityThreadPool; /** * The Timer used to time out requests for long polling. */ private final HashedWheelTimer requestTimer; // Expose Stats private final BKStats bkStats = BKStats.getInstance(); private final boolean statsEnabled; private final RequestStats requestStats; final Semaphore addsSemaphore; final Semaphore readsSemaphore; final ChannelGroup allChannels; // to temporary blacklist channels final Optional<Cache<Channel, Boolean>> blacklistedChannels; final Consumer<Channel> onResponseTimeout; private final ByteBufAllocator allocator; private final boolean throttleReadResponses; public BookieRequestProcessor(ServerConfiguration serverCfg, Bookie bookie, StatsLogger statsLogger, SecurityHandlerFactory shFactory, ByteBufAllocator allocator, ChannelGroup allChannels) throws SecurityException { this.serverCfg = serverCfg; this.allocator = allocator; this.allChannels = allChannels; this.waitTimeoutOnBackpressureMillis = serverCfg.getWaitTimeoutOnResponseBackpressureMillis(); this.preserveMdcForTaskExecution = serverCfg.getPreserveMdcForTaskExecution(); this.bookie = bookie; this.throttleReadResponses = serverCfg.isReadWorkerThreadsThrottlingEnabled(); this.readThreadPool = createExecutor( this.serverCfg.getNumReadWorkerThreads(), "BookieReadThreadPool", serverCfg.getMaxPendingReadRequestPerThread(), statsLogger); this.writeThreadPool = createExecutor( this.serverCfg.getNumAddWorkerThreads(), "BookieWriteThreadPool", serverCfg.getMaxPendingAddRequestPerThread(), statsLogger); if (serverCfg.getNumLongPollWorkerThreads() <= 0 && readThreadPool != null) { this.longPollThreadPool = this.readThreadPool; } else { int numThreads = this.serverCfg.getNumLongPollWorkerThreads(); if (numThreads <= 0) { numThreads = Runtime.getRuntime().availableProcessors(); } this.longPollThreadPool = createExecutor( numThreads, "BookieLongPollThread", OrderedExecutor.NO_TASK_LIMIT, statsLogger); } this.highPriorityThreadPool = createExecutor( this.serverCfg.getNumHighPriorityWorkerThreads(), "BookieHighPriorityThread", OrderedExecutor.NO_TASK_LIMIT, statsLogger); this.shFactory = shFactory; if (shFactory != null) { shFactory.init(NodeType.Server, serverCfg, allocator); } this.requestTimer = new HashedWheelTimer( new ThreadFactoryBuilder().setNameFormat("BookieRequestTimer-%d").build(), this.serverCfg.getRequestTimerTickDurationMs(), TimeUnit.MILLISECONDS, this.serverCfg.getRequestTimerNumTicks()); if (waitTimeoutOnBackpressureMillis > 0) { blacklistedChannels = Optional.of(CacheBuilder.newBuilder() .expireAfterWrite(waitTimeoutOnBackpressureMillis, TimeUnit.MILLISECONDS) .build()); } else { blacklistedChannels = Optional.empty(); } if (serverCfg.getCloseChannelOnResponseTimeout()) { onResponseTimeout = (ch) -> { LOG.warn("closing channel {} because it was non-writable for longer than {} ms", ch, waitTimeoutOnBackpressureMillis); ch.close(); }; } else { // noop onResponseTimeout = (ch) -> {}; } // Expose Stats this.statsEnabled = serverCfg.isStatisticsEnabled(); this.requestStats = new RequestStats(statsLogger); int maxAdds = serverCfg.getMaxAddsInProgressLimit(); addsSemaphore = maxAdds > 0 ? new Semaphore(maxAdds, true) : null; int maxReads = serverCfg.getMaxReadsInProgressLimit(); readsSemaphore = maxReads > 0 ? new Semaphore(maxReads, true) : null; } protected void onAddRequestStart(Channel channel) { if (addsSemaphore != null) { if (!addsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); LOG.info("Too many add requests in progress, disabling autoread on channel {}", channel); requestStats.blockAddRequest(); addsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); final long delayNanos = MathUtils.elapsedNanos(throttlingStartTimeNanos); LOG.info("Re-enabled autoread on channel {} after AddRequest delay of {} nanos", channel, delayNanos); requestStats.unblockAddRequest(delayNanos); } } requestStats.trackAddRequest(); } protected void onAddRequestFinish() { requestStats.untrackAddRequest(); if (addsSemaphore != null) { addsSemaphore.release(); } } protected void onReadRequestStart(Channel channel) { if (readsSemaphore != null) { if (!readsSemaphore.tryAcquire()) { final long throttlingStartTimeNanos = MathUtils.nowInNano(); channel.config().setAutoRead(false); LOG.info("Too many read requests in progress, disabling autoread on channel {}", channel); requestStats.blockReadRequest(); readsSemaphore.acquireUninterruptibly(); channel.config().setAutoRead(true); final long delayNanos = MathUtils.elapsedNanos(throttlingStartTimeNanos); LOG.info("Re-enabled autoread on channel {} after ReadRequest delay of {} nanos", channel, delayNanos); requestStats.unblockReadRequest(delayNanos); } } requestStats.trackReadRequest(); } protected void onReadRequestFinish() { requestStats.untrackReadRequest(); if (readsSemaphore != null) { readsSemaphore.release(); } } @VisibleForTesting int maxAddsInProgressCount() { return requestStats.maxAddsInProgressCount(); } @VisibleForTesting int maxReadsInProgressCount() { return requestStats.maxReadsInProgressCount(); } @Override public void close() { LOG.info("Closing RequestProcessor"); shutdownExecutor(writeThreadPool); shutdownExecutor(readThreadPool); if (serverCfg.getNumLongPollWorkerThreads() > 0 || readThreadPool == null) { shutdownExecutor(longPollThreadPool); } shutdownExecutor(highPriorityThreadPool); requestTimer.stop(); LOG.info("Closed RequestProcessor"); } private OrderedExecutor createExecutor( int numThreads, String nameFormat, int maxTasksInQueue, StatsLogger statsLogger) { if (numThreads <= 0) { return null; } else { return OrderedExecutor.newBuilder() .numThreads(numThreads) .name(nameFormat) .traceTaskExecution(serverCfg.getEnableTaskExecutionStats()) .preserveMdcForTaskExecution(serverCfg.getPreserveMdcForTaskExecution()) .statsLogger(statsLogger) .maxTasksInQueue(maxTasksInQueue) .enableThreadScopedMetrics(true) .build(); } } private void shutdownExecutor(OrderedExecutor service) { if (null != service) { service.shutdown(); service.forceShutdown(10, TimeUnit.SECONDS); } } @Override public void processRequest(Object msg, BookieRequestHandler requestHandler) { Channel channel = requestHandler.ctx().channel(); // If we can decode this packet as a Request protobuf packet, process // it as a version 3 packet. Else, just use the old protocol. if (msg instanceof BookkeeperProtocol.Request) { BookkeeperProtocol.Request r = (BookkeeperProtocol.Request) msg; restoreMdcContextFromRequest(r); try { BookkeeperProtocol.BKPacketHeader header = r.getHeader(); switch (header.getOperation()) { case ADD_ENTRY: processAddRequestV3(r, requestHandler); break; case READ_ENTRY: processReadRequestV3(r, requestHandler); break; case FORCE_LEDGER: processForceLedgerRequestV3(r, requestHandler); break; case AUTH: LOG.info("Ignoring auth operation from client {}", channel.remoteAddress()); BookkeeperProtocol.AuthMessage message = BookkeeperProtocol.AuthMessage .newBuilder() .setAuthPluginName(AuthProviderFactoryFactory.AUTHENTICATION_DISABLED_PLUGIN_NAME) .setPayload(ByteString.copyFrom(AuthToken.NULL.getData())) .build(); final BookkeeperProtocol.Response authResponse = BookkeeperProtocol.Response .newBuilder().setHeader(r.getHeader()) .setStatus(BookkeeperProtocol.StatusCode.EOK) .setAuthResponse(message) .build(); writeAndFlush(channel, authResponse); break; case WRITE_LAC: processWriteLacRequestV3(r, requestHandler); break; case READ_LAC: processReadLacRequestV3(r, requestHandler); break; case GET_BOOKIE_INFO: processGetBookieInfoRequestV3(r, requestHandler); break; case START_TLS: processStartTLSRequestV3(r, requestHandler); break; case GET_LIST_OF_ENTRIES_OF_LEDGER: processGetListOfEntriesOfLedgerProcessorV3(r, requestHandler); break; default: LOG.info("Unknown operation type {}", header.getOperation()); final BookkeeperProtocol.Response response = BookkeeperProtocol.Response.newBuilder().setHeader(r.getHeader()) .setStatus(BookkeeperProtocol.StatusCode.EBADREQ) .build(); writeAndFlush(channel, response); if (statsEnabled) { bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps(); } break; } } finally { MDC.clear(); } } else { BookieProtocol.Request r = (BookieProtocol.Request) msg; // process packet switch (r.getOpCode()) { case BookieProtocol.ADDENTRY: checkArgument(r instanceof BookieProtocol.ParsedAddRequest); processAddRequest((BookieProtocol.ParsedAddRequest) r, requestHandler); break; case BookieProtocol.READENTRY: checkArgument(r instanceof BookieProtocol.ReadRequest); processReadRequest((BookieProtocol.ReadRequest) r, requestHandler); break; case BookieProtocol.AUTH: LOG.info("Ignoring auth operation from client {}", requestHandler.ctx().channel().remoteAddress()); BookkeeperProtocol.AuthMessage message = BookkeeperProtocol.AuthMessage .newBuilder() .setAuthPluginName(AuthProviderFactoryFactory.AUTHENTICATION_DISABLED_PLUGIN_NAME) .setPayload(ByteString.copyFrom(AuthToken.NULL.getData())) .build(); final BookieProtocol.AuthResponse response = new BookieProtocol.AuthResponse( BookieProtocol.CURRENT_PROTOCOL_VERSION, message); writeAndFlush(channel, response); break; default: LOG.error("Unknown op type {}, sending error", r.getOpCode()); final BookieProtocol.Response errResponse = ResponseBuilder .buildErrorResponse(BookieProtocol.EBADREQ, r); writeAndFlush(channel, errResponse); if (statsEnabled) { bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps(); } break; } } } private void restoreMdcContextFromRequest(BookkeeperProtocol.Request req) { if (preserveMdcForTaskExecution) { MDC.clear(); for (BookkeeperProtocol.ContextPair pair: req.getRequestContextList()) { MDC.put(pair.getKey(), pair.getValue()); } } } private void processWriteLacRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { WriteLacProcessorV3 writeLac = new WriteLacProcessorV3(r, requestHandler, this); if (null == writeThreadPool) { writeLac.run(); } else { writeThreadPool.executeOrdered(r.getAddRequest().getLedgerId(), writeLac); } } private void processReadLacRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { ReadLacProcessorV3 readLac = new ReadLacProcessorV3(r, requestHandler, this); if (null == readThreadPool) { readLac.run(); } else { readThreadPool.executeOrdered(r.getAddRequest().getLedgerId(), readLac); } } private void processAddRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { WriteEntryProcessorV3 write = new WriteEntryProcessorV3(r, requestHandler, this); final OrderedExecutor threadPool; if (RequestUtils.isHighPriority(r)) { threadPool = highPriorityThreadPool; } else { threadPool = writeThreadPool; } if (null == threadPool) { write.run(); } else { try { threadPool.executeOrdered(r.getAddRequest().getLedgerId(), write); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to process request to add entry at {}:{}. Too many pending requests", r.getAddRequest().getLedgerId(), r.getAddRequest().getEntryId()); } getRequestStats().getAddEntryRejectedCounter().inc(); BookkeeperProtocol.AddResponse.Builder addResponse = BookkeeperProtocol.AddResponse.newBuilder() .setLedgerId(r.getAddRequest().getLedgerId()) .setEntryId(r.getAddRequest().getEntryId()) .setStatus(BookkeeperProtocol.StatusCode.ETOOMANYREQUESTS); BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder() .setHeader(write.getHeader()) .setStatus(addResponse.getStatus()) .setAddResponse(addResponse); BookkeeperProtocol.Response resp = response.build(); write.sendResponse(addResponse.getStatus(), resp, requestStats.getAddRequestStats()); } } } private void processForceLedgerRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { ForceLedgerProcessorV3 forceLedger = new ForceLedgerProcessorV3(r, requestHandler, this); final OrderedExecutor threadPool; if (RequestUtils.isHighPriority(r)) { threadPool = highPriorityThreadPool; } else { threadPool = writeThreadPool; } if (null == threadPool) { forceLedger.run(); } else { try { threadPool.executeOrdered(r.getForceLedgerRequest().getLedgerId(), forceLedger); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to process request to force ledger {}. Too many pending requests", r.getForceLedgerRequest().getLedgerId()); } BookkeeperProtocol.ForceLedgerResponse.Builder forceLedgerResponse = BookkeeperProtocol.ForceLedgerResponse.newBuilder() .setLedgerId(r.getForceLedgerRequest().getLedgerId()) .setStatus(BookkeeperProtocol.StatusCode.ETOOMANYREQUESTS); BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder() .setHeader(forceLedger.getHeader()) .setStatus(forceLedgerResponse.getStatus()) .setForceLedgerResponse(forceLedgerResponse); BookkeeperProtocol.Response resp = response.build(); forceLedger.sendResponse( forceLedgerResponse.getStatus(), resp, requestStats.getForceLedgerRequestStats()); } } } private void processReadRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { ExecutorService fenceThread = null == highPriorityThreadPool ? null : highPriorityThreadPool.chooseThread(requestHandler.ctx()); final ReadEntryProcessorV3 read; final OrderedExecutor threadPool; if (RequestUtils.isLongPollReadRequest(r.getReadRequest())) { ExecutorService lpThread = longPollThreadPool.chooseThread(requestHandler.ctx()); read = new LongPollReadEntryProcessorV3(r, requestHandler, this, fenceThread, lpThread, requestTimer); threadPool = longPollThreadPool; } else { read = new ReadEntryProcessorV3(r, requestHandler, this, fenceThread); // If it's a high priority read (fencing or as part of recovery process), we want to make sure it // gets executed as fast as possible, so bypass the normal readThreadPool // and execute in highPriorityThreadPool boolean isHighPriority = RequestUtils.isHighPriority(r) || hasFlag(r.getReadRequest(), BookkeeperProtocol.ReadRequest.Flag.FENCE_LEDGER); if (isHighPriority) { threadPool = highPriorityThreadPool; } else { threadPool = readThreadPool; } } if (null == threadPool) { read.run(); } else { try { threadPool.executeOrdered(r.getReadRequest().getLedgerId(), read); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to process request to read entry at {}:{}. Too many pending requests", r.getReadRequest().getLedgerId(), r.getReadRequest().getEntryId()); } getRequestStats().getReadEntryRejectedCounter().inc(); BookkeeperProtocol.ReadResponse.Builder readResponse = BookkeeperProtocol.ReadResponse.newBuilder() .setLedgerId(r.getReadRequest().getLedgerId()) .setEntryId(r.getReadRequest().getEntryId()) .setStatus(BookkeeperProtocol.StatusCode.ETOOMANYREQUESTS); BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder() .setHeader(read.getHeader()) .setStatus(readResponse.getStatus()) .setReadResponse(readResponse); BookkeeperProtocol.Response resp = response.build(); read.sendResponse(readResponse.getStatus(), resp, requestStats.getReadRequestStats()); onReadRequestFinish(); } } } private void processStartTLSRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder(); BookkeeperProtocol.BKPacketHeader.Builder header = BookkeeperProtocol.BKPacketHeader.newBuilder(); header.setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE); header.setOperation(r.getHeader().getOperation()); header.setTxnId(r.getHeader().getTxnId()); response.setHeader(header.build()); final Channel c = requestHandler.ctx().channel(); if (shFactory == null) { LOG.error("Got StartTLS request but TLS not configured"); response.setStatus(BookkeeperProtocol.StatusCode.EBADREQ); writeAndFlush(c, response.build()); } else { // there is no need to execute in a different thread as this operation is light SslHandler sslHandler = shFactory.newTLSHandler(); c.pipeline().addFirst("tls", sslHandler); response.setStatus(BookkeeperProtocol.StatusCode.EOK); BookkeeperProtocol.StartTLSResponse.Builder builder = BookkeeperProtocol.StartTLSResponse.newBuilder(); response.setStartTLSResponse(builder.build()); sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { // notify the AuthPlugin the completion of the handshake, even in case of failure AuthHandler.ServerSideHandler authHandler = c.pipeline() .get(AuthHandler.ServerSideHandler.class); authHandler.authProvider.onProtocolUpgrade(); /* * Success of the future doesn't guarantee success in authentication * future.isSuccess() only checks if the result field is not null */ if (future.isSuccess() && authHandler.isAuthenticated()) { LOG.info("Session is protected by: {}", sslHandler.engine().getSession().getCipherSuite()); } else { if (future.isSuccess()) { LOG.error("TLS Handshake failed: Could not authenticate."); } else { LOG.error("TLS Handshake failure: ", future.cause()); } final BookkeeperProtocol.Response errResponse = BookkeeperProtocol.Response.newBuilder() .setHeader(r.getHeader()) .setStatus(BookkeeperProtocol.StatusCode.EIO) .build(); writeAndFlush(c, errResponse); if (statsEnabled) { bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps(); } } } }); writeAndFlush(c, response.build()); } } private void processGetBookieInfoRequestV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { GetBookieInfoProcessorV3 getBookieInfo = new GetBookieInfoProcessorV3(r, requestHandler, this); if (null == readThreadPool) { getBookieInfo.run(); } else { readThreadPool.submit(getBookieInfo); } } private void processGetListOfEntriesOfLedgerProcessorV3(final BookkeeperProtocol.Request r, final BookieRequestHandler requestHandler) { GetListOfEntriesOfLedgerProcessorV3 getListOfEntriesOfLedger = new GetListOfEntriesOfLedgerProcessorV3(r, requestHandler, this); if (null == readThreadPool) { getListOfEntriesOfLedger.run(); } else { readThreadPool.submit(getListOfEntriesOfLedger); } } private void processAddRequest(final BookieProtocol.ParsedAddRequest r, final BookieRequestHandler requestHandler) { WriteEntryProcessor write = WriteEntryProcessor.create(r, requestHandler, this); // If it's a high priority add (usually as part of recovery process), we want to make sure it gets // executed as fast as possible, so bypass the normal writeThreadPool and execute in highPriorityThreadPool final OrderedExecutor threadPool; if (r.isHighPriority()) { threadPool = highPriorityThreadPool; } else { threadPool = writeThreadPool; } if (null == threadPool) { write.run(); } else { try { threadPool.executeOrdered(r.getLedgerId(), write); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to process request to add entry at {}:{}. Too many pending requests", r.ledgerId, r.entryId); } getRequestStats().getAddEntryRejectedCounter().inc(); write.sendWriteReqResponse( BookieProtocol.ETOOMANYREQUESTS, ResponseBuilder.buildErrorResponse(BookieProtocol.ETOOMANYREQUESTS, r), requestStats.getAddRequestStats()); r.release(); r.recycle(); write.recycle(); } } } private void processReadRequest(final BookieProtocol.ReadRequest r, final BookieRequestHandler requestHandler) { ExecutorService fenceThreadPool = null == highPriorityThreadPool ? null : highPriorityThreadPool.chooseThread(requestHandler.ctx()); ReadEntryProcessor read = ReadEntryProcessor.create(r, requestHandler, this, fenceThreadPool, throttleReadResponses); // If it's a high priority read (fencing or as part of recovery process), we want to make sure it // gets executed as fast as possible, so bypass the normal readThreadPool // and execute in highPriorityThreadPool final OrderedExecutor threadPool; if (r.isHighPriority() || r.isFencing()) { threadPool = highPriorityThreadPool; } else { threadPool = readThreadPool; } if (null == threadPool) { read.run(); } else { try { threadPool.executeOrdered(r.getLedgerId(), read); } catch (RejectedExecutionException e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to process request to read entry at {}:{}. Too many pending requests", r.ledgerId, r.entryId); } getRequestStats().getReadEntryRejectedCounter().inc(); read.sendResponse( BookieProtocol.ETOOMANYREQUESTS, ResponseBuilder.buildErrorResponse(BookieProtocol.ETOOMANYREQUESTS, r), requestStats.getReadRequestStats()); onReadRequestFinish(); read.recycle(); } } } public long getWaitTimeoutOnBackpressureMillis() { return waitTimeoutOnBackpressureMillis; } public void blacklistChannel(Channel channel) { blacklistedChannels .ifPresent(x -> x.put(channel, true)); } public void invalidateBlacklist(Channel channel) { blacklistedChannels .ifPresent(x -> x.invalidate(channel)); } public boolean isBlacklisted(Channel channel) { return blacklistedChannels .map(x -> x.getIfPresent(channel)) .orElse(false); } public void handleNonWritableChannel(Channel channel) { onResponseTimeout.accept(channel); } private static void writeAndFlush(Channel channel, Object msg) { NettyChannelUtil.writeAndFlushWithVoidPromise(channel, msg); } }
84
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ResponseBuilder.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.proto; import io.netty.buffer.ByteBuf; class ResponseBuilder { static BookieProtocol.Response buildErrorResponse(int errorCode, BookieProtocol.Request r) { if (r.getOpCode() == BookieProtocol.ADDENTRY) { return BookieProtocol.AddResponse.create(r.getProtocolVersion(), errorCode, r.getLedgerId(), r.getEntryId()); } else { assert(r.getOpCode() == BookieProtocol.READENTRY); return new BookieProtocol.ReadResponse(r.getProtocolVersion(), errorCode, r.getLedgerId(), r.getEntryId()); } } static BookieProtocol.Response buildAddResponse(BookieProtocol.Request r) { return BookieProtocol.AddResponse.create(r.getProtocolVersion(), BookieProtocol.EOK, r.getLedgerId(), r.getEntryId()); } static BookieProtocol.Response buildReadResponse(ByteBuf data, BookieProtocol.Request r) { return new BookieProtocol.ReadResponse(r.getProtocolVersion(), BookieProtocol.EOK, r.getLedgerId(), r.getEntryId(), data); } }
85
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieAddressResolver.java
/* * Copyright 2020 The Apache Software Foundation. * * Licensed 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.proto; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; /** * Maps a logical BookieId to a ResolvedBookieSocketAddress that it to a network address. */ public interface BookieAddressResolver { /** * Maps a logical address to a network address. * @param bookieId * @return a mapped address. * @throws BookieIdNotResolvedException if it is not possible to resolve the address of the BookieId */ BookieSocketAddress resolve(BookieId bookieId) throws BookieIdNotResolvedException; /** * This error happens when there is not enough information to resolve a BookieId * to a BookieSocketAddress, this can happen when the Bookie is down * and it is not publishing its EndpointInfo. */ class BookieIdNotResolvedException extends RuntimeException { private final BookieId bookieId; public BookieIdNotResolvedException(BookieId bookieId, Throwable cause) { super("Cannot resolve bookieId " + bookieId + ", bookie does not exist or it is not running", cause); this.bookieId = bookieId; } public BookieId getBookieId() { return bookieId; } } }
86
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieProtoEncoding.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.proto; import com.google.protobuf.CodedOutputStream; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageLite; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.ByteBufInputStream; import io.netty.buffer.ByteBufOutputStream; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import java.security.NoSuchAlgorithmException; import org.apache.bookkeeper.proto.BookieProtocol.PacketHeader; import org.apache.bookkeeper.proto.BookkeeperProtocol.OperationType; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.checksum.MacDigestManager; import org.apache.bookkeeper.util.ByteBufList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A class for encoding and decoding the Bookkeeper protocol. */ public class BookieProtoEncoding { private static final Logger LOG = LoggerFactory.getLogger(BookieProtoEncoding.class); /** * Threshold under which an entry is considered to be "small". * * Small entries payloads are copied instead of being passed around as references. */ public static final int SMALL_ENTRY_SIZE_THRESHOLD = 16 * 1024; /** * An encoder/decoder interface for the Bookkeeper protocol. */ public interface EnDecoder { /** * Encode a <i>object</i> into channel buffer. * * @param object * object. * @return encode buffer. * @throws Exception */ Object encode(Object object, ByteBufAllocator allocator) throws Exception; /** * Decode a <i>packet</i> into an object. * * @param packet * received packet. * @return parsed object. * @throws Exception */ Object decode(ByteBuf packet) throws Exception; } /** * An encoder/decoder for the Bookkeeper protocol before version 3. */ public static class RequestEnDeCoderPreV3 implements EnDecoder { final ExtensionRegistry extensionRegistry; //This empty master key is used when an empty password is provided which is the hash of an empty string private static final byte[] emptyPasswordMasterKey; static { try { emptyPasswordMasterKey = MacDigestManager.genDigest("ledger", new byte[0]); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } public RequestEnDeCoderPreV3(ExtensionRegistry extensionRegistry) { this.extensionRegistry = extensionRegistry; } @Override public Object encode(Object msg, ByteBufAllocator allocator) throws Exception { if (!(msg instanceof BookieProtocol.Request)) { return msg; } BookieProtocol.Request r = (BookieProtocol.Request) msg; if (r instanceof BookieProtocol.ReadRequest) { int totalHeaderSize = 4 // for request type + 8 // for ledgerId + 8; // for entryId if (r.hasMasterKey()) { totalHeaderSize += BookieProtocol.MASTER_KEY_LENGTH; } ByteBuf buf = allocator.buffer(totalHeaderSize + 4 /* frame size */); buf.writeInt(totalHeaderSize); buf.writeInt(PacketHeader.toInt(r.getProtocolVersion(), r.getOpCode(), r.getFlags())); buf.writeLong(r.getLedgerId()); buf.writeLong(r.getEntryId()); if (r.hasMasterKey()) { buf.writeBytes(r.getMasterKey(), 0, BookieProtocol.MASTER_KEY_LENGTH); } r.recycle(); return buf; } else if (r instanceof BookieProtocol.AuthRequest) { BookkeeperProtocol.AuthMessage am = ((BookieProtocol.AuthRequest) r).getAuthMessage(); int totalHeaderSize = 4; // for request type int totalSize = totalHeaderSize + am.getSerializedSize(); ByteBuf buf = allocator.buffer(totalSize + 4 /* frame size */); buf.writeInt(totalSize); buf.writeInt(PacketHeader.toInt(r.getProtocolVersion(), r.getOpCode(), r.getFlags())); ByteBufOutputStream bufStream = new ByteBufOutputStream(buf); am.writeTo(bufStream); return buf; } else { return msg; } } @Override public Object decode(ByteBuf packet) throws Exception { int packetHeader = packet.readInt(); byte version = PacketHeader.getVersion(packetHeader); byte opCode = PacketHeader.getOpCode(packetHeader); short flags = PacketHeader.getFlags(packetHeader); // packet format is different between ADDENTRY and READENTRY long ledgerId = -1; long entryId = BookieProtocol.INVALID_ENTRY_ID; switch (opCode) { case BookieProtocol.ADDENTRY: { byte[] masterKey = readMasterKey(packet); // Read ledger and entry id without advancing the reader index ledgerId = packet.getLong(packet.readerIndex()); entryId = packet.getLong(packet.readerIndex() + 8); // mark the reader index so that any resets will return to the // start of the payload packet.markReaderIndex(); return BookieProtocol.ParsedAddRequest.create( version, ledgerId, entryId, flags, masterKey, packet); } case BookieProtocol.READENTRY: ledgerId = packet.readLong(); entryId = packet.readLong(); if ((flags & BookieProtocol.FLAG_DO_FENCING) == BookieProtocol.FLAG_DO_FENCING && version >= 2) { byte[] masterKey = readMasterKey(packet); return BookieProtocol.ReadRequest.create(version, ledgerId, entryId, flags, masterKey); } else { return BookieProtocol.ReadRequest.create(version, ledgerId, entryId, flags, null); } case BookieProtocol.AUTH: BookkeeperProtocol.AuthMessage.Builder builder = BookkeeperProtocol.AuthMessage.newBuilder(); builder.mergeFrom(new ByteBufInputStream(packet), extensionRegistry); return new BookieProtocol.AuthRequest(version, builder.build()); default: throw new IllegalStateException("Received unknown request op code = " + opCode); } } private static byte[] readMasterKey(ByteBuf packet) { byte[] masterKey = null; // check if the master key is an empty master key boolean isEmptyKey = true; for (int i = 0; i < BookieProtocol.MASTER_KEY_LENGTH; i++) { if (packet.getByte(packet.readerIndex() + i) != emptyPasswordMasterKey[i]) { isEmptyKey = false; break; } } if (isEmptyKey) { // avoid new allocations if incoming master key is empty and use the static master key masterKey = emptyPasswordMasterKey; packet.readerIndex(packet.readerIndex() + BookieProtocol.MASTER_KEY_LENGTH); } else { // Master key is set, we need to copy and check it masterKey = new byte[BookieProtocol.MASTER_KEY_LENGTH]; packet.readBytes(masterKey, 0, BookieProtocol.MASTER_KEY_LENGTH); } return masterKey; } } /** * A response encoder/decoder for the Bookkeeper protocol before version 3. */ public static class ResponseEnDeCoderPreV3 implements EnDecoder { final ExtensionRegistry extensionRegistry; public ResponseEnDeCoderPreV3(ExtensionRegistry extensionRegistry) { this.extensionRegistry = extensionRegistry; } private static final int RESPONSE_HEADERS_SIZE = 24; @Override public Object encode(Object msg, ByteBufAllocator allocator) throws Exception { if (!(msg instanceof BookieProtocol.Response)) { return msg; } BookieProtocol.Response r = (BookieProtocol.Response) msg; try { if (msg instanceof BookieProtocol.ReadResponse) { BookieProtocol.ReadResponse rr = (BookieProtocol.ReadResponse) r; int payloadSize = rr.getData().readableBytes(); int responseSize = RESPONSE_HEADERS_SIZE + payloadSize; boolean isSmallEntry = payloadSize < SMALL_ENTRY_SIZE_THRESHOLD; int bufferSize = 4 /* frame size */ + RESPONSE_HEADERS_SIZE + (isSmallEntry ? payloadSize : 0); ByteBuf buf = allocator.buffer(bufferSize); buf.writeInt(responseSize); buf.writeInt(PacketHeader.toInt(r.getProtocolVersion(), r.getOpCode(), (short) 0)); buf.writeInt(r.getErrorCode()); buf.writeLong(r.getLedgerId()); buf.writeLong(r.getEntryId()); if (isSmallEntry) { buf.writeBytes(rr.getData()); rr.release(); return buf; } else { return ByteBufList.get(buf, rr.getData()); } } else if (msg instanceof BookieProtocol.AddResponse) { ByteBuf buf = allocator.buffer(RESPONSE_HEADERS_SIZE + 4 /* frame size */); buf.writeInt(RESPONSE_HEADERS_SIZE); buf.writeInt(PacketHeader.toInt(r.getProtocolVersion(), r.getOpCode(), (short) 0)); buf.writeInt(r.getErrorCode()); buf.writeLong(r.getLedgerId()); buf.writeLong(r.getEntryId()); return buf; } else if (msg instanceof BookieProtocol.AuthResponse) { BookkeeperProtocol.AuthMessage am = ((BookieProtocol.AuthResponse) r).getAuthMessage(); int payloadSize = 4 + am.getSerializedSize(); int bufferSize = payloadSize + 4 /* frame size */; ByteBuf buf = allocator.buffer(bufferSize); buf.writeInt(payloadSize); buf.writeInt(PacketHeader.toInt(r.getProtocolVersion(), r.getOpCode(), (short) 0)); buf.writeBytes(am.toByteArray()); return buf; } else { LOG.error("Cannot encode unknown response type {}", msg.getClass().getName()); return msg; } } finally { r.recycle(); } } @Override public Object decode(ByteBuf buffer) throws Exception { int rc; long ledgerId, entryId; int packetHeader = buffer.readInt(); byte version = PacketHeader.getVersion(packetHeader); byte opCode = PacketHeader.getOpCode(packetHeader); switch (opCode) { case BookieProtocol.ADDENTRY: rc = buffer.readInt(); ledgerId = buffer.readLong(); entryId = buffer.readLong(); return BookieProtocol.AddResponse.create(version, rc, ledgerId, entryId); case BookieProtocol.READENTRY: rc = buffer.readInt(); ledgerId = buffer.readLong(); entryId = buffer.readLong(); return new BookieProtocol.ReadResponse( version, rc, ledgerId, entryId, buffer.retainedSlice()); case BookieProtocol.AUTH: ByteBufInputStream bufStream = new ByteBufInputStream(buffer); BookkeeperProtocol.AuthMessage.Builder builder = BookkeeperProtocol.AuthMessage.newBuilder(); builder.mergeFrom(bufStream, extensionRegistry); BookkeeperProtocol.AuthMessage am = builder.build(); return new BookieProtocol.AuthResponse(version, am); default: throw new IllegalStateException("Received unknown response : op code = " + opCode); } } public static void serializeAddResponseInto(int rc, BookieProtocol.ParsedAddRequest req, ByteBuf buf) { buf.writeInt(RESPONSE_HEADERS_SIZE); // Frame size buf.writeInt(PacketHeader.toInt(req.getProtocolVersion(), req.getOpCode(), (short) 0)); buf.writeInt(rc); // rc-code buf.writeLong(req.getLedgerId()); buf.writeLong(req.getEntryId()); } } /** * A request encoder/decoder for the Bookkeeper protocol version 3. */ public static class RequestEnDecoderV3 implements EnDecoder { final ExtensionRegistry extensionRegistry; public RequestEnDecoderV3(ExtensionRegistry extensionRegistry) { this.extensionRegistry = extensionRegistry; } @Override public Object decode(ByteBuf packet) throws Exception { return BookkeeperProtocol.Request.parseFrom(new ByteBufInputStream(packet), extensionRegistry); } @Override public Object encode(Object msg, ByteBufAllocator allocator) throws Exception { BookkeeperProtocol.Request request = (BookkeeperProtocol.Request) msg; return serializeProtobuf(request, allocator); } } /** * A response encoder/decoder for the Bookkeeper protocol version 3. */ public static class ResponseEnDecoderV3 implements EnDecoder { final ExtensionRegistry extensionRegistry; public ResponseEnDecoderV3(ExtensionRegistry extensionRegistry) { this.extensionRegistry = extensionRegistry; } @Override public Object decode(ByteBuf packet) throws Exception { return BookkeeperProtocol.Response.parseFrom(new ByteBufInputStream(packet), extensionRegistry); } @Override public Object encode(Object msg, ByteBufAllocator allocator) throws Exception { BookkeeperProtocol.Response response = (BookkeeperProtocol.Response) msg; return serializeProtobuf(response, allocator); } } private static ByteBuf serializeProtobuf(MessageLite msg, ByteBufAllocator allocator) { int size = msg.getSerializedSize(); int frameSize = size + 4; // Protobuf serialization is the last step of the netty pipeline. We used to allocate // a heap buffer while serializing and pass it down to netty library. // In AbstractChannel#filterOutboundMessage(), netty copies that data to a direct buffer if // it is currently in heap (otherwise skips it and uses it directly). // Allocating a direct buffer reducing unncessary CPU cycles for buffer copies in BK client // and also helps alleviate pressure off the GC, since there is less memory churn. // Bookies aren't usually CPU bound. This change improves READ_ENTRY code paths by a small factor as well. ByteBuf buf = allocator.directBuffer(frameSize, frameSize); buf.writeInt(size); try { msg.writeTo(CodedOutputStream.newInstance(buf.nioBuffer(buf.writerIndex(), size))); } catch (IOException e) { // This is in-memory serialization, should not fail throw new RuntimeException(e); } // Advance writer idx buf.writerIndex(frameSize); return buf; } /** * A request message encoder. */ @Sharable public static class RequestEncoder extends ChannelOutboundHandlerAdapter { final EnDecoder reqPreV3; final EnDecoder reqV3; public RequestEncoder(ExtensionRegistry extensionRegistry) { reqPreV3 = new RequestEnDeCoderPreV3(extensionRegistry); reqV3 = new RequestEnDecoderV3(extensionRegistry); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Encode request {} to channel {}.", msg, ctx.channel()); } if (msg instanceof ByteBuf || msg instanceof ByteBufList) { ctx.write(msg, promise); } else if (msg instanceof BookkeeperProtocol.Request) { ctx.write(reqV3.encode(msg, ctx.alloc()), promise); } else if (msg instanceof BookieProtocol.Request) { ctx.write(reqPreV3.encode(msg, ctx.alloc()), promise); } else { LOG.error("Invalid request to encode to {}: {}", ctx.channel(), msg.getClass().getName()); ctx.write(msg, promise); } } } /** * A request message decoder. */ @Sharable public static class RequestDecoder extends ChannelInboundHandlerAdapter { final EnDecoder reqPreV3; final EnDecoder reqV3; boolean usingV3Protocol; RequestDecoder(ExtensionRegistry extensionRegistry) { reqPreV3 = new RequestEnDeCoderPreV3(extensionRegistry); reqV3 = new RequestEnDecoderV3(extensionRegistry); usingV3Protocol = true; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Received request {} from channel {} to decode.", msg, ctx.channel()); } try { if (!(msg instanceof ByteBuf)) { LOG.error("Received invalid request {} from channel {} to decode.", msg, ctx.channel()); ctx.fireChannelRead(msg); return; } ByteBuf buffer = (ByteBuf) msg; buffer.markReaderIndex(); Object result; if (usingV3Protocol) { try { result = reqV3.decode(buffer); } catch (InvalidProtocolBufferException e) { usingV3Protocol = false; buffer.resetReaderIndex(); result = reqPreV3.decode(buffer); } } else { result = reqPreV3.decode(buffer); } ctx.fireChannelRead(result); } finally { ReferenceCountUtil.release(msg); } } } /** * A response message encoder. */ @Sharable public static class ResponseEncoder extends ChannelOutboundHandlerAdapter { final EnDecoder repPreV3; final EnDecoder repV3; ResponseEncoder(ExtensionRegistry extensionRegistry) { repPreV3 = new ResponseEnDeCoderPreV3(extensionRegistry); repV3 = new ResponseEnDecoderV3(extensionRegistry); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Encode response {} to channel {}.", msg, ctx.channel()); } if (msg instanceof ByteBuf) { ctx.write(msg, promise); } else if (msg instanceof BookkeeperProtocol.Response) { ctx.write(repV3.encode(msg, ctx.alloc()), promise); } else if (msg instanceof BookieProtocol.Response) { ctx.write(repPreV3.encode(msg, ctx.alloc()), promise); } else { LOG.error("Invalid response to encode to {}: {}", ctx.channel(), msg.getClass().getName()); ctx.write(msg, promise); } } } /** * A response message decoder. */ @Sharable public static class ResponseDecoder extends ChannelInboundHandlerAdapter { final EnDecoder repPreV3; final EnDecoder repV3; final boolean useV2Protocol; final boolean tlsEnabled; boolean usingV3Protocol; ResponseDecoder(ExtensionRegistry extensionRegistry, boolean useV2Protocol, boolean tlsEnabled) { this.repPreV3 = new ResponseEnDeCoderPreV3(extensionRegistry); this.repV3 = new ResponseEnDecoderV3(extensionRegistry); this.useV2Protocol = useV2Protocol; this.tlsEnabled = tlsEnabled; usingV3Protocol = true; } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (LOG.isTraceEnabled()) { LOG.trace("Received response {} from channel {} to decode.", msg, ctx.channel()); } try { if (!(msg instanceof ByteBuf)) { LOG.error("Received invalid response {} from channel {} to decode.", msg, ctx.channel()); ctx.fireChannelRead(msg); return; } ByteBuf buffer = (ByteBuf) msg; buffer.markReaderIndex(); Object result; if (!useV2Protocol) { // always use v3 protocol result = repV3.decode(buffer); } else { // use v2 protocol but // if TLS enabled, the first message `startTLS` is a protobuf message if (tlsEnabled && usingV3Protocol) { try { result = repV3.decode(buffer); if (result instanceof Response && OperationType.START_TLS == ((Response) result).getHeader().getOperation()) { usingV3Protocol = false; if (LOG.isDebugEnabled()) { LOG.debug("Degrade bookkeeper to v2 after starting TLS."); } } } catch (InvalidProtocolBufferException e) { usingV3Protocol = false; buffer.resetReaderIndex(); result = repPreV3.decode(buffer); } } else { result = repPreV3.decode(buffer); } } ctx.fireChannelRead(result); } finally { ReferenceCountUtil.release(msg); } } } }
87
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/LocalBookiesRegistry.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.proto; import java.util.concurrent.ConcurrentHashMap; import org.apache.bookkeeper.net.BookieId; /** * Local registry for embedded Bookies. */ public class LocalBookiesRegistry { private static final ConcurrentHashMap<BookieId, Boolean> localBookiesRegistry = new ConcurrentHashMap<>(); static void registerLocalBookieAddress(BookieId address) { localBookiesRegistry.put(address, Boolean.TRUE); } static void unregisterLocalBookieAddress(BookieId address) { if (address != null) { localBookiesRegistry.remove(address); } } public static boolean isLocalBookie(BookieId address) { return localBookiesRegistry.containsKey(address); } }
88
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/WriteLacProcessorV3.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.proto; import io.netty.buffer.Unpooled; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.proto.BookkeeperProtocol.WriteLacRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.WriteLacResponse; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class WriteLacProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private static final Logger logger = LoggerFactory.getLogger(WriteLacProcessorV3.class); public WriteLacProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); } // Returns null if there is no exception thrown private WriteLacResponse getWriteLacResponse() { final long startTimeNanos = MathUtils.nowInNano(); WriteLacRequest writeLacRequest = request.getWriteLacRequest(); long lac = writeLacRequest.getLac(); long ledgerId = writeLacRequest.getLedgerId(); final WriteLacResponse.Builder writeLacResponse = WriteLacResponse.newBuilder().setLedgerId(ledgerId); if (!isVersionCompatible()) { writeLacResponse.setStatus(StatusCode.EBADVERSION); return writeLacResponse.build(); } if (requestProcessor.bookie.isReadOnly()) { logger.warn("BookieServer is running as readonly mode, so rejecting the request from the client!"); writeLacResponse.setStatus(StatusCode.EREADONLY); return writeLacResponse.build(); } BookkeeperInternalCallbacks.WriteCallback writeCallback = new BookkeeperInternalCallbacks.WriteCallback() { @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) { if (BookieProtocol.EOK == rc) { requestProcessor.getRequestStats().getWriteLacStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getWriteLacStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } StatusCode status; switch (rc) { case BookieProtocol.EOK: status = StatusCode.EOK; break; case BookieProtocol.EIO: status = StatusCode.EIO; break; default: status = StatusCode.EUA; break; } writeLacResponse.setStatus(status); Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(writeLacResponse.getStatus()) .setWriteLacResponse(writeLacResponse); Response resp = response.build(); sendResponse(status, resp, requestProcessor.getRequestStats().getWriteLacRequestStats()); } }; StatusCode status = null; ByteBuffer lacToAdd = writeLacRequest.getBody().asReadOnlyByteBuffer(); byte[] masterKey = writeLacRequest.getMasterKey().toByteArray(); try { requestProcessor.bookie.setExplicitLac(Unpooled.wrappedBuffer(lacToAdd), writeCallback, requestHandler, masterKey); status = StatusCode.EOK; } catch (IOException e) { logger.error("Error saving lac {} for ledger:{}", lac, ledgerId, e); status = StatusCode.EIO; } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Interrupted while saving lac {} for ledger:{}", lac, ledgerId, e); status = StatusCode.EIO; } catch (BookieException e) { logger.error("Unauthorized access to ledger:{} while adding lac:{}", ledgerId, lac, e); status = StatusCode.EUA; } catch (Throwable t) { logger.error("Unexpected exception while writing lac {} for ledger:{}", lac, ledgerId, t); // some bad request which cause unexpected exception status = StatusCode.EBADREQ; } // If everything is okay, we return null so that the calling function // dosn't return a response back to the caller. if (!status.equals(StatusCode.EOK)) { requestProcessor.getRequestStats().getWriteLacStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); writeLacResponse.setStatus(status); return writeLacResponse.build(); } return null; } @Override public void run() { WriteLacResponse writeLacResponse = getWriteLacResponse(); if (null != writeLacResponse) { Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(writeLacResponse.getStatus()) .setWriteLacResponse(writeLacResponse); Response resp = response.build(); sendResponse( writeLacResponse.getStatus(), resp, requestProcessor.getRequestStats().getWriteLacRequestStats()); } } /** * this toString method filters out body and masterKey from the output. * masterKey contains the password of the ledger and body is customer data, * so it is not appropriate to have these in logs or system output. */ @Override public String toString() { return RequestUtils.toSafeString(request); } }
89
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClientFactory.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.proto; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.tls.SecurityException; import org.apache.bookkeeper.tls.SecurityHandlerFactory; /** * Factory to create {@link org.apache.bookkeeper.proto.PerChannelBookieClient}. */ interface PerChannelBookieClientFactory { /** * Create a {@link org.apache.bookkeeper.proto.PerChannelBookieClient} to * <i>address</i>. * * @return the client connected to address. * @throws SecurityException */ PerChannelBookieClient create(BookieId address, PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory, boolean forceUseV3) throws SecurityException; }
90
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieClient.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.proto; import io.netty.util.ReferenceCounted; import java.util.EnumSet; import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.bookkeeper.client.api.WriteFlag; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ForceLedgerCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GetBookieInfoCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadLacCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteLacCallback; import org.apache.bookkeeper.util.AvailabilityOfEntriesOfLedger; import org.apache.bookkeeper.util.ByteBufList; /** * Low level client for talking to bookies. */ public interface BookieClient { long PENDINGREQ_NOTWRITABLE_MASK = 0x01L << 62; /** * Get the list of bookies which have exhibited more error responses * than a configured threshold. * * @return the list of faulty bookies */ List<BookieId> getFaultyBookies(); /** * Check whether the channel used to write to a bookie channel is writable. * A channel becomes non-writable when its buffer become full, and will stay * non-writable until some of the buffer is cleared. * * <p>This can be used to apply backpressure. If a channel is not writable, * requests will end up queuing. * * <p>As as we use pooling, there may be multiple channels per bookie, so * we also pass the ledger ID to check the writability of the correct * channel. * * <p>This has nothing to do with the bookie read-only status. * * @param address the address of the bookie * @param ledgerId the ledger we wish to send a request to * */ boolean isWritable(BookieId address, long ledgerId); /** * Get the number of outstanding requests on the channel used to connect * to a bookie at {@code address} for a ledger with {@code ledgerId}. * It is necessary to specify the ledgerId as there may be multiple * channels for a single bookie if pooling is in use. * If the bookie is not {@link #isWritable(BookieId,long) writable}, * then the {@link #PENDINGREQ_NOTWRITABLE_MASK} will be logically or'd with * the returned value. * * @param address the address of the bookie * @param ledgerId the ledger whose channel we wish to query * @return the number of requests currently outstanding */ long getNumPendingRequests(BookieId address, long ledgerId); /** * Send a force request to the server. When complete all entries which have * been written for {@code ledgerId} to this bookie will be persisted on disk. * This is for use with {@link org.apache.bookkeeper.client.api.WriteFlag#DEFERRED_SYNC}. * * @param address the address of the bookie * @param ledgerId the ledger whose entries we want persisted * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion */ void forceLedger(BookieId address, long ledgerId, ForceLedgerCallback cb, Object ctx); /** * Read the last add confirmed for ledger {@code ledgerId} from the bookie at * {@code address}. * * @param address the address of the bookie * @param ledgerId the ledger whose last add confirm we wish to know * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion */ void readLac(BookieId address, long ledgerId, ReadLacCallback cb, Object ctx); /** * Explicitly write the last add confirmed for ledger {@code ledgerId} to the bookie at * {@code address}. * * @param address the address of the bookie * @param ledgerId the ledger whose last add confirm we wish to know * @param masterKey the master key of the ledger * @param lac the last add confirmed we wish to write * @param toSend a buffer also containing the lac, along with a digest * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion */ void writeLac(BookieId address, long ledgerId, byte[] masterKey, long lac, ByteBufList toSend, WriteLacCallback cb, Object ctx); /** * Add an entry for ledger {@code ledgerId} on the bookie at address {@code address}. * * @param address the address of the bookie * @param ledgerId the ledger to which we wish to add the entry * @param entryId the id of the entry we wish to add * @param toSend a buffer containing the entry and its digest * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion * @param options a bit mask of flags from BookieProtocol.FLAG_* * {@link org.apache.bookkeeper.proto.BookieProtocol} * @param allowFastFail fail the add immediately if the channel is non-writable * {@link #isWritable(BookieId,long)} * @param writeFlags a set of write flags * {@link org.apache.bookkeeper.client.api.WriteFlag} */ void addEntry(BookieId address, long ledgerId, byte[] masterKey, long entryId, ReferenceCounted toSend, WriteCallback cb, Object ctx, int options, boolean allowFastFail, EnumSet<WriteFlag> writeFlags); /** * Read entry with a null masterkey, disallowing failfast. * @see #readEntry(BookieId,long,long,ReadEntryCallback,Object,int,byte[],boolean) */ default void readEntry(BookieId address, long ledgerId, long entryId, ReadEntryCallback cb, Object ctx, int flags) { readEntry(address, ledgerId, entryId, cb, ctx, flags, null); } /** * Read entry, disallowing failfast. * @see #readEntry(BookieId,long,long,ReadEntryCallback,Object,int,byte[],boolean) */ default void readEntry(BookieId address, long ledgerId, long entryId, ReadEntryCallback cb, Object ctx, int flags, byte[] masterKey) { readEntry(address, ledgerId, entryId, cb, ctx, flags, masterKey, false); } /** * Read an entry from bookie at address {@code address}. * * @param address address of the bookie to read from * @param ledgerId id of the ledger the entry belongs to * @param entryId id of the entry we wish to read * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion * @param flags a bit mask of flags from BookieProtocol.FLAG_* * {@link org.apache.bookkeeper.proto.BookieProtocol} * @param masterKey the master key of the ledger being read from. This is only required * if the FLAG_DO_FENCING is specified. * @param allowFastFail fail the read immediately if the channel is non-writable * {@link #isWritable(BookieId,long)} */ void readEntry(BookieId address, long ledgerId, long entryId, ReadEntryCallback cb, Object ctx, int flags, byte[] masterKey, boolean allowFastFail); /** * Send a long poll request to bookie, waiting for the last add confirmed * to be updated. The client can also request that the full entry is returned * with the new last add confirmed. * * @param address address of bookie to send the long poll address to * @param ledgerId ledger whose last add confirmed we are interested in * @param entryId the id of the entry we expect to read * @param previousLAC the previous lac value * @param timeOutInMillis number of millis to wait for LAC update * @param piggyBackEntry whether to read the requested entry when LAC is updated * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion */ void readEntryWaitForLACUpdate(BookieId address, long ledgerId, long entryId, long previousLAC, long timeOutInMillis, boolean piggyBackEntry, ReadEntryCallback cb, Object ctx); /** * Read information about the bookie, from the bookie. * * @param address the address of the bookie to request information from * @param requested a bitset specifying which pieces of information to request * {@link org.apache.bookkeeper.proto.BookkeeperProtocol.GetBookieInfoRequest} * @param cb the callback notified when the request completes * @param ctx a context object passed to the callback on completion * * @see org.apache.bookkeeper.client.BookieInfoReader.BookieInfo */ void getBookieInfo(BookieId address, long requested, GetBookieInfoCallback cb, Object ctx); /** * Makes async request for getting list of entries of ledger from a bookie * and returns Future for the result. * * @param address * BookieId of the bookie * @param ledgerId * ledgerId * @return returns Future */ CompletableFuture<AvailabilityOfEntriesOfLedger> getListOfEntriesOfLedger(BookieId address, long ledgerId); /** * @return whether bookie client object has been closed */ boolean isClosed(); /** * Close the bookie client object. */ void close(); }
91
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/WriteEntryProcessorV3.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.proto; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import java.io.IOException; import java.util.EnumSet; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieException.OperationRejectedException; import org.apache.bookkeeper.client.api.WriteFlag; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.AddResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class WriteEntryProcessorV3 extends PacketProcessorBaseV3 { private static final Logger logger = LoggerFactory.getLogger(WriteEntryProcessorV3.class); public WriteEntryProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); requestProcessor.onAddRequestStart(requestHandler.ctx().channel()); } // Returns null if there is no exception thrown private AddResponse getAddResponse() { final long startTimeNanos = MathUtils.nowInNano(); AddRequest addRequest = request.getAddRequest(); long ledgerId = addRequest.getLedgerId(); long entryId = addRequest.getEntryId(); final AddResponse.Builder addResponse = AddResponse.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); if (!isVersionCompatible()) { addResponse.setStatus(StatusCode.EBADVERSION); return addResponse.build(); } if (requestProcessor.getBookie().isReadOnly() && !(RequestUtils.isHighPriority(request) && requestProcessor.getBookie().isAvailableForHighPriorityWrites())) { logger.warn("BookieServer is running as readonly mode, so rejecting the request from the client!"); addResponse.setStatus(StatusCode.EREADONLY); return addResponse.build(); } BookkeeperInternalCallbacks.WriteCallback wcb = new BookkeeperInternalCallbacks.WriteCallback() { @Override public void writeComplete(int rc, long ledgerId, long entryId, BookieId addr, Object ctx) { if (BookieProtocol.EOK == rc) { requestProcessor.getRequestStats().getAddEntryStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getAddEntryStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } StatusCode status; switch (rc) { case BookieProtocol.EOK: status = StatusCode.EOK; break; case BookieProtocol.EIO: status = StatusCode.EIO; break; default: status = StatusCode.EUA; break; } addResponse.setStatus(status); Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(addResponse.getStatus()) .setAddResponse(addResponse); Response resp = response.build(); sendResponse(status, resp, requestProcessor.getRequestStats().getAddRequestStats()); } }; final EnumSet<WriteFlag> writeFlags; if (addRequest.hasWriteFlags()) { writeFlags = WriteFlag.getWriteFlags(addRequest.getWriteFlags()); } else { writeFlags = WriteFlag.NONE; } final boolean ackBeforeSync = writeFlags.contains(WriteFlag.DEFERRED_SYNC); StatusCode status = null; byte[] masterKey = addRequest.getMasterKey().toByteArray(); ByteBuf entryToAdd = Unpooled.wrappedBuffer(addRequest.getBody().asReadOnlyByteBuffer()); try { if (RequestUtils.hasFlag(addRequest, AddRequest.Flag.RECOVERY_ADD)) { requestProcessor.getBookie().recoveryAddEntry(entryToAdd, wcb, requestHandler.ctx().channel(), masterKey); } else { requestProcessor.getBookie().addEntry(entryToAdd, ackBeforeSync, wcb, requestHandler.ctx().channel(), masterKey); } status = StatusCode.EOK; } catch (OperationRejectedException e) { requestProcessor.getRequestStats().getAddEntryRejectedCounter().inc(); // Avoid to log each occurence of this exception as this can happen when the ledger storage is // unable to keep up with the write rate. if (logger.isDebugEnabled()) { logger.debug("Operation rejected while writing {}", request, e); } status = StatusCode.ETOOMANYREQUESTS; } catch (IOException e) { logger.error("Error writing entry:{} to ledger:{}", entryId, ledgerId, e); status = StatusCode.EIO; } catch (BookieException.LedgerFencedException e) { logger.error("Ledger fenced while writing entry:{} to ledger:{}", entryId, ledgerId, e); status = StatusCode.EFENCED; } catch (BookieException e) { logger.error("Unauthorized access to ledger:{} while writing entry:{}", ledgerId, entryId, e); status = StatusCode.EUA; } catch (Throwable t) { logger.error("Unexpected exception while writing {}@{} : ", entryId, ledgerId, t); // some bad request which cause unexpected exception status = StatusCode.EBADREQ; } // If everything is okay, we return null so that the calling function // doesn't return a response back to the caller. if (!status.equals(StatusCode.EOK)) { addResponse.setStatus(status); return addResponse.build(); } return null; } @Override public void run() { requestProcessor.getRequestStats().getWriteThreadQueuedLatency() .registerSuccessfulEvent(MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); AddResponse addResponse = getAddResponse(); if (null != addResponse) { // This means there was an error and we should send this back. Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(addResponse.getStatus()) .setAddResponse(addResponse); Response resp = response.build(); sendResponse(addResponse.getStatus(), resp, requestProcessor.getRequestStats().getAddRequestStats()); } } @Override protected void sendResponse(StatusCode code, Object response, OpStatsLogger statsLogger) { super.sendResponse(code, response, statsLogger); requestProcessor.onAddRequestFinish(); } /** * this toString method filters out body and masterKey from the output. * masterKey contains the password of the ledger and body is customer data, * so it is not appropriate to have these in logs or system output. */ @Override public String toString() { return RequestUtils.toSafeString(request); } }
92
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ReadEntryProcessorV3.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.proto; import com.google.common.base.Stopwatch; import com.google.protobuf.ByteString; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.util.ReferenceCountUtil; import java.io.IOException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.common.concurrent.FutureEventListener; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class ReadEntryProcessorV3 extends PacketProcessorBaseV3 { private static final Logger LOG = LoggerFactory.getLogger(ReadEntryProcessorV3.class); protected Stopwatch lastPhaseStartTime; private final ExecutorService fenceThreadPool; private CompletableFuture<Boolean> fenceResult = null; protected final ReadRequest readRequest; protected final long ledgerId; protected final long entryId; // Stats protected final OpStatsLogger readStats; protected final OpStatsLogger reqStats; public ReadEntryProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor, ExecutorService fenceThreadPool) { super(request, requestHandler, requestProcessor); requestProcessor.onReadRequestStart(requestHandler.ctx().channel()); this.readRequest = request.getReadRequest(); this.ledgerId = readRequest.getLedgerId(); this.entryId = readRequest.getEntryId(); if (RequestUtils.isFenceRequest(this.readRequest)) { this.readStats = requestProcessor.getRequestStats().getFenceReadEntryStats(); this.reqStats = requestProcessor.getRequestStats().getFenceReadRequestStats(); } else if (readRequest.hasPreviousLAC()) { this.readStats = requestProcessor.getRequestStats().getLongPollReadStats(); this.reqStats = requestProcessor.getRequestStats().getLongPollReadRequestStats(); } else { this.readStats = requestProcessor.getRequestStats().getReadEntryStats(); this.reqStats = requestProcessor.getRequestStats().getReadRequestStats(); } this.fenceThreadPool = fenceThreadPool; lastPhaseStartTime = Stopwatch.createStarted(); } protected Long getPreviousLAC() { if (readRequest.hasPreviousLAC()) { return readRequest.getPreviousLAC(); } else { return null; } } /** * Handle read result for fence read. * * @param entryBody * read result * @param readResponseBuilder * read response builder * @param entryId * entry id * @param startTimeSw * timer for the read request */ protected void handleReadResultForFenceRead( final ByteBuf entryBody, final ReadResponse.Builder readResponseBuilder, final long entryId, final Stopwatch startTimeSw) { // reset last phase start time to measure fence result waiting time lastPhaseStartTime.reset().start(); if (null != fenceThreadPool) { fenceResult.whenCompleteAsync(new FutureEventListener<Boolean>() { @Override public void onSuccess(Boolean result) { sendFenceResponse(readResponseBuilder, entryBody, result, startTimeSw); } @Override public void onFailure(Throwable t) { LOG.error("Fence request for ledgerId {} entryId {} encountered exception", ledgerId, entryId, t); sendFenceResponse(readResponseBuilder, entryBody, false, startTimeSw); } }, fenceThreadPool); } else { boolean success = false; try { success = fenceResult.get(1000, TimeUnit.MILLISECONDS); } catch (Throwable t) { LOG.error("Fence request for ledgerId {} entryId {} encountered exception : ", readRequest.getLedgerId(), readRequest.getEntryId(), t); } sendFenceResponse(readResponseBuilder, entryBody, success, startTimeSw); } } /** * Read a specific entry. * * @param readResponseBuilder * read response builder. * @param entryId * entry to read * @param startTimeSw * stop watch to measure the read operation. * @return read response or null if it is a fence read operation. * @throws IOException */ protected ReadResponse readEntry(ReadResponse.Builder readResponseBuilder, long entryId, Stopwatch startTimeSw) throws IOException, BookieException { return readEntry(readResponseBuilder, entryId, false, startTimeSw); } /** * Read a specific entry. * * @param readResponseBuilder * read response builder. * @param entryId * entry to read * @param startTimeSw * stop watch to measure the read operation. * @return read response or null if it is a fence read operation. * @throws IOException */ protected ReadResponse readEntry(ReadResponse.Builder readResponseBuilder, long entryId, boolean readLACPiggyBack, Stopwatch startTimeSw) throws IOException, BookieException { ByteBuf entryBody = requestProcessor.getBookie().readEntry(ledgerId, entryId); if (null != fenceResult) { handleReadResultForFenceRead(entryBody, readResponseBuilder, entryId, startTimeSw); return null; } else { try { readResponseBuilder.setBody(ByteString.copyFrom(entryBody.nioBuffer())); if (readLACPiggyBack) { readResponseBuilder.setEntryId(entryId); } else { long knownLAC = requestProcessor.getBookie().readLastAddConfirmed(ledgerId); readResponseBuilder.setMaxLAC(knownLAC); } registerSuccessfulEvent(readStats, startTimeSw); readResponseBuilder.setStatus(StatusCode.EOK); return readResponseBuilder.build(); } finally { ReferenceCountUtil.release(entryBody); } } } protected ReadResponse getReadResponse() { final Stopwatch startTimeSw = Stopwatch.createStarted(); final Channel channel = requestHandler.ctx().channel(); final ReadResponse.Builder readResponse = ReadResponse.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); try { // handle fence reqest if (RequestUtils.isFenceRequest(readRequest)) { LOG.info("Ledger fence request received for ledger: {} from address: {}", ledgerId, channel.remoteAddress()); if (!readRequest.hasMasterKey()) { LOG.error( "Fence ledger request received without master key for ledger:{} from address: {}", ledgerId, channel.remoteAddress()); throw BookieException.create(BookieException.Code.UnauthorizedAccessException); } else { byte[] masterKey = readRequest.getMasterKey().toByteArray(); fenceResult = requestProcessor.bookie.fenceLedger(ledgerId, masterKey); } } return readEntry(readResponse, entryId, startTimeSw); } catch (Bookie.NoLedgerException e) { if (RequestUtils.isFenceRequest(readRequest)) { LOG.info("No ledger found reading entry {} when fencing ledger {}", entryId, ledgerId); } else if (entryId != BookieProtocol.LAST_ADD_CONFIRMED) { LOG.info("No ledger found while reading entry: {} from ledger: {}", entryId, ledgerId); } else if (LOG.isDebugEnabled()) { // this is the case of a reader which is calling readLastAddConfirmed and the ledger is empty LOG.debug("No ledger found while reading entry: {} from ledger: {}", entryId, ledgerId); } return buildResponse(readResponse, StatusCode.ENOLEDGER, startTimeSw); } catch (Bookie.NoEntryException e) { if (LOG.isDebugEnabled()) { LOG.debug("No entry found while reading entry: {} from ledger: {}", entryId, ledgerId); } return buildResponse(readResponse, StatusCode.ENOENTRY, startTimeSw); } catch (IOException e) { LOG.error("IOException while reading entry: {} from ledger {} ", entryId, ledgerId, e); return buildResponse(readResponse, StatusCode.EIO, startTimeSw); } catch (BookieException.DataUnknownException e) { if (LOG.isDebugEnabled()) { LOG.debug("Ledger has unknown state for entry: {} from ledger {}", entryId, ledgerId); } return buildResponse(readResponse, StatusCode.EUNKNOWNLEDGERSTATE, startTimeSw); } catch (BookieException e) { LOG.error( "Unauthorized access to ledger:{} while reading entry:{} in request from address: {}", ledgerId, entryId, channel.remoteAddress()); return buildResponse(readResponse, StatusCode.EUA, startTimeSw); } } @Override public void run() { requestProcessor.getRequestStats().getReadEntrySchedulingDelayStats().registerSuccessfulEvent( MathUtils.elapsedNanos(enqueueNanos), TimeUnit.NANOSECONDS); if (!requestHandler.ctx().channel().isOpen()) { if (LOG.isDebugEnabled()) { LOG.debug("Dropping read request for closed channel: {}", requestHandler.ctx().channel()); } requestProcessor.onReadRequestFinish(); return; } if (!isVersionCompatible()) { ReadResponse readResponse = ReadResponse.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId) .setStatus(StatusCode.EBADVERSION) .build(); sendResponse(readResponse); return; } executeOp(); } protected void executeOp() { ReadResponse readResponse = getReadResponse(); if (null != readResponse) { sendResponse(readResponse); } } private void getFenceResponse(ReadResponse.Builder readResponse, ByteBuf entryBody, boolean fenceResult) { StatusCode status; if (!fenceResult) { status = StatusCode.EIO; registerFailedEvent(requestProcessor.getRequestStats().getFenceReadWaitStats(), lastPhaseStartTime); } else { status = StatusCode.EOK; readResponse.setBody(ByteString.copyFrom(entryBody.nioBuffer())); registerSuccessfulEvent(requestProcessor.getRequestStats().getFenceReadWaitStats(), lastPhaseStartTime); } if (null != entryBody) { ReferenceCountUtil.release(entryBody); } readResponse.setStatus(status); } private void sendFenceResponse(ReadResponse.Builder readResponse, ByteBuf entryBody, boolean fenceResult, Stopwatch startTimeSw) { // build the fence read response getFenceResponse(readResponse, entryBody, fenceResult); // register fence read stat registerEvent(!fenceResult, requestProcessor.getRequestStats().getFenceReadEntryStats(), startTimeSw); // send the fence read response sendResponse(readResponse.build()); } protected ReadResponse buildResponse( ReadResponse.Builder readResponseBuilder, StatusCode statusCode, Stopwatch startTimeSw) { registerEvent(!statusCode.equals(StatusCode.EOK), readStats, startTimeSw); readResponseBuilder.setStatus(statusCode); return readResponseBuilder.build(); } protected void sendResponse(ReadResponse readResponse) { Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(readResponse.getStatus()) .setReadResponse(readResponse); sendResponse(response.getStatus(), response.build(), reqStats); requestProcessor.onReadRequestFinish(); } // // Stats Methods // protected void registerSuccessfulEvent(OpStatsLogger statsLogger, Stopwatch startTime) { registerEvent(false, statsLogger, startTime); } protected void registerFailedEvent(OpStatsLogger statsLogger, Stopwatch startTime) { registerEvent(true, statsLogger, startTime); } protected void registerEvent(boolean failed, OpStatsLogger statsLogger, Stopwatch startTime) { if (failed) { statsLogger.registerFailedEvent(startTime.elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); } else { statsLogger.registerSuccessfulEvent(startTime.elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS); } } /** * this toString method filters out masterKey from the output. masterKey * contains the password of the ledger. */ @Override public String toString() { return RequestUtils.toSafeString(request); } }
93
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/RequestStats.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.proto; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY_BLOCKED; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY_BLOCKED_WAIT; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY_IN_PROGRESS; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY_REJECTED; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.ADD_ENTRY_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.CATEGORY_SERVER; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.CHANNEL_WRITE; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.FORCE_LEDGER; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.FORCE_LEDGER_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.GET_BOOKIE_INFO; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.GET_BOOKIE_INFO_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.GET_LIST_OF_ENTRIES_OF_LEDGER; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.GET_LIST_OF_ENTRIES_OF_LEDGER_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_BLOCKED; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_BLOCKED_WAIT; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_FENCE_READ; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_FENCE_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_FENCE_WAIT; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_IN_PROGRESS; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_LONG_POLL_PRE_WAIT; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_LONG_POLL_READ; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_LONG_POLL_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_LONG_POLL_WAIT; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_REJECTED; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_ENTRY_SCHEDULING_DELAY; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_LAC; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_LAC_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.READ_LAST_ENTRY_NOENTRY_ERROR; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.SERVER_SCOPE; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.WRITE_LAC; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.WRITE_LAC_REQUEST; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.WRITE_THREAD_QUEUED_LATENCY; import java.util.concurrent.TimeUnit; 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; /** * A umbrella class for request related stats. */ @StatsDoc( name = SERVER_SCOPE, category = CATEGORY_SERVER, help = "Bookie request stats" ) @Getter public class RequestStats { final AtomicInteger addsInProgress = new AtomicInteger(0); final AtomicInteger maxAddsInProgress = new AtomicInteger(0); final AtomicInteger addsBlocked = new AtomicInteger(0); final AtomicInteger readsInProgress = new AtomicInteger(0); final AtomicInteger readsBlocked = new AtomicInteger(0); final AtomicInteger maxReadsInProgress = new AtomicInteger(0); @StatsDoc( name = ADD_ENTRY_REQUEST, help = "request stats of AddEntry on a bookie" ) private final OpStatsLogger addRequestStats; @StatsDoc( name = ADD_ENTRY, help = "operation stats of AddEntry on a bookie", parent = ADD_ENTRY_REQUEST ) private final OpStatsLogger addEntryStats; @StatsDoc( name = WRITE_THREAD_QUEUED_LATENCY, help = "operation stats of enqueuing requests to write threadpool queue", parent = ADD_ENTRY_REQUEST ) private final OpStatsLogger writeThreadQueuedLatency; @StatsDoc( name = ADD_ENTRY_REJECTED, help = "Counter for rejected adds on a bookie", parent = ADD_ENTRY_REQUEST ) private final Counter addEntryRejectedCounter; @StatsDoc( name = READ_ENTRY_REQUEST, help = "request stats of ReadEntry on a bookie" ) final OpStatsLogger readRequestStats; @StatsDoc( name = READ_ENTRY, help = "operation stats of ReadEntry on a bookie", parent = READ_ENTRY_REQUEST ) final OpStatsLogger readEntryStats; @StatsDoc( name = READ_ENTRY_REJECTED, help = "Counter for rejected reads on a bookie", parent = READ_ENTRY_REQUEST ) private final Counter readEntryRejectedCounter; @StatsDoc( name = FORCE_LEDGER, help = "operation stats of ForceLedger on a bookie", parent = FORCE_LEDGER_REQUEST ) final OpStatsLogger forceLedgerStats; @StatsDoc( name = FORCE_LEDGER_REQUEST, help = "request stats of ForceLedger on a bookie" ) final OpStatsLogger forceLedgerRequestStats; @StatsDoc( name = READ_ENTRY_FENCE_REQUEST, help = "request stats of FenceRead on a bookie" ) final OpStatsLogger fenceReadRequestStats; @StatsDoc( name = READ_ENTRY_FENCE_READ, help = "operation stats of FenceRead on a bookie", parent = READ_ENTRY_FENCE_REQUEST, happensAfter = READ_ENTRY_FENCE_WAIT ) final OpStatsLogger fenceReadEntryStats; @StatsDoc( name = READ_ENTRY_FENCE_WAIT, help = "operation stats of FenceReadWait on a bookie", parent = READ_ENTRY_FENCE_REQUEST ) final OpStatsLogger fenceReadWaitStats; @StatsDoc( name = READ_ENTRY_SCHEDULING_DELAY, help = "operation stats of ReadEntry scheduling delays on a bookie" ) final OpStatsLogger readEntrySchedulingDelayStats; @StatsDoc( name = READ_ENTRY_LONG_POLL_PRE_WAIT, help = "operation stats of LongPoll Reads pre wait time on a bookie", parent = READ_ENTRY_LONG_POLL_REQUEST ) final OpStatsLogger longPollPreWaitStats; @StatsDoc( name = READ_ENTRY_LONG_POLL_WAIT, help = "operation stats of LongPoll Reads wait time on a bookie", happensAfter = READ_ENTRY_LONG_POLL_PRE_WAIT, parent = READ_ENTRY_LONG_POLL_REQUEST ) final OpStatsLogger longPollWaitStats; @StatsDoc( name = READ_ENTRY_LONG_POLL_READ, help = "operation stats of LongPoll Reads on a bookie", happensAfter = READ_ENTRY_LONG_POLL_WAIT, parent = READ_ENTRY_LONG_POLL_REQUEST ) final OpStatsLogger longPollReadStats; @StatsDoc( name = READ_ENTRY_LONG_POLL_REQUEST, help = "request stats of LongPoll Reads on a bookie" ) final OpStatsLogger longPollReadRequestStats; @StatsDoc( name = READ_LAST_ENTRY_NOENTRY_ERROR, help = "total NOENTRY errors of reading last entry on a bookie" ) final Counter readLastEntryNoEntryErrorCounter; @StatsDoc( name = WRITE_LAC_REQUEST, help = "request stats of WriteLac on a bookie" ) final OpStatsLogger writeLacRequestStats; @StatsDoc( name = WRITE_LAC, help = "operation stats of WriteLac on a bookie", parent = WRITE_LAC_REQUEST ) final OpStatsLogger writeLacStats; @StatsDoc( name = READ_LAC_REQUEST, help = "request stats of ReadLac on a bookie" ) final OpStatsLogger readLacRequestStats; @StatsDoc( name = READ_LAC, help = "operation stats of ReadLac on a bookie", parent = READ_LAC_REQUEST ) final OpStatsLogger readLacStats; @StatsDoc( name = GET_BOOKIE_INFO_REQUEST, help = "request stats of GetBookieInfo on a bookie" ) final OpStatsLogger getBookieInfoRequestStats; @StatsDoc( name = GET_BOOKIE_INFO, help = "operation stats of GetBookieInfo on a bookie" ) final OpStatsLogger getBookieInfoStats; @StatsDoc( name = CHANNEL_WRITE, help = "channel write stats on a bookie" ) final OpStatsLogger channelWriteStats; @StatsDoc( name = ADD_ENTRY_BLOCKED, help = "operation stats of AddEntry blocked on a bookie" ) final OpStatsLogger addEntryBlockedStats; @StatsDoc( name = READ_ENTRY_BLOCKED, help = "operation stats of ReadEntry blocked on a bookie" ) final OpStatsLogger readEntryBlockedStats; @StatsDoc( name = GET_LIST_OF_ENTRIES_OF_LEDGER_REQUEST, help = "request stats of GetListOfEntriesOfLedger on a bookie" ) final OpStatsLogger getListOfEntriesOfLedgerRequestStats; @StatsDoc( name = "GET_LIST_OF_ENTRIES_OF_LEDGER", help = "operation stats of GetListOfEntriesOfLedger", parent = GET_LIST_OF_ENTRIES_OF_LEDGER_REQUEST ) final OpStatsLogger getListOfEntriesOfLedgerStats; public RequestStats(StatsLogger statsLogger) { this.addEntryStats = statsLogger.getThreadScopedOpStatsLogger(ADD_ENTRY); this.writeThreadQueuedLatency = statsLogger.getThreadScopedOpStatsLogger(WRITE_THREAD_QUEUED_LATENCY); this.addRequestStats = statsLogger.getOpStatsLogger(ADD_ENTRY_REQUEST); this.addEntryRejectedCounter = statsLogger.getCounter(ADD_ENTRY_REJECTED); this.readEntryStats = statsLogger.getThreadScopedOpStatsLogger(READ_ENTRY); this.readEntryRejectedCounter = statsLogger.getCounter(READ_ENTRY_REJECTED); this.forceLedgerStats = statsLogger.getOpStatsLogger(FORCE_LEDGER); this.forceLedgerRequestStats = statsLogger.getOpStatsLogger(FORCE_LEDGER_REQUEST); this.readRequestStats = statsLogger.getOpStatsLogger(READ_ENTRY_REQUEST); this.fenceReadEntryStats = statsLogger.getOpStatsLogger(READ_ENTRY_FENCE_READ); this.fenceReadRequestStats = statsLogger.getOpStatsLogger(READ_ENTRY_FENCE_REQUEST); this.fenceReadWaitStats = statsLogger.getOpStatsLogger(READ_ENTRY_FENCE_WAIT); this.readEntrySchedulingDelayStats = statsLogger.getOpStatsLogger(READ_ENTRY_SCHEDULING_DELAY); this.longPollPreWaitStats = statsLogger.getOpStatsLogger(READ_ENTRY_LONG_POLL_PRE_WAIT); this.longPollWaitStats = statsLogger.getOpStatsLogger(READ_ENTRY_LONG_POLL_WAIT); this.longPollReadStats = statsLogger.getOpStatsLogger(READ_ENTRY_LONG_POLL_READ); this.longPollReadRequestStats = statsLogger.getOpStatsLogger(READ_ENTRY_LONG_POLL_REQUEST); this.readLastEntryNoEntryErrorCounter = statsLogger.getCounter(READ_LAST_ENTRY_NOENTRY_ERROR); this.writeLacStats = statsLogger.getOpStatsLogger(WRITE_LAC); this.writeLacRequestStats = statsLogger.getOpStatsLogger(WRITE_LAC_REQUEST); this.readLacStats = statsLogger.getOpStatsLogger(READ_LAC); this.readLacRequestStats = statsLogger.getOpStatsLogger(READ_LAC_REQUEST); this.getBookieInfoStats = statsLogger.getOpStatsLogger(GET_BOOKIE_INFO); this.getBookieInfoRequestStats = statsLogger.getOpStatsLogger(GET_BOOKIE_INFO_REQUEST); this.channelWriteStats = statsLogger.getOpStatsLogger(CHANNEL_WRITE); this.addEntryBlockedStats = statsLogger.getOpStatsLogger(ADD_ENTRY_BLOCKED_WAIT); this.readEntryBlockedStats = statsLogger.getOpStatsLogger(READ_ENTRY_BLOCKED_WAIT); this.getListOfEntriesOfLedgerStats = statsLogger.getOpStatsLogger(GET_LIST_OF_ENTRIES_OF_LEDGER); this.getListOfEntriesOfLedgerRequestStats = statsLogger.getOpStatsLogger(GET_LIST_OF_ENTRIES_OF_LEDGER_REQUEST); statsLogger.registerGauge(ADD_ENTRY_IN_PROGRESS, new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return addsInProgress; } }); statsLogger.registerGauge(ADD_ENTRY_BLOCKED, new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return addsBlocked; } }); statsLogger.registerGauge(READ_ENTRY_IN_PROGRESS, new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return readsInProgress; } }); statsLogger.registerGauge(READ_ENTRY_BLOCKED, new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return readsBlocked; } }); } // // Add requests // void blockAddRequest() { addsBlocked.incrementAndGet(); } void unblockAddRequest(long delayNanos) { addEntryBlockedStats.registerSuccessfulEvent(delayNanos, TimeUnit.NANOSECONDS); addsBlocked.decrementAndGet(); } void trackAddRequest() { final int curr = addsInProgress.incrementAndGet(); maxAddsInProgress.accumulateAndGet(curr, Integer::max); } void untrackAddRequest() { addsInProgress.decrementAndGet(); } int maxAddsInProgressCount() { return maxAddsInProgress.get(); } // // Read requests // void blockReadRequest() { readsBlocked.incrementAndGet(); } void unblockReadRequest(long delayNanos) { readEntryBlockedStats.registerSuccessfulEvent(delayNanos, TimeUnit.NANOSECONDS); readsBlocked.decrementAndGet(); } void trackReadRequest() { final int curr = readsInProgress.incrementAndGet(); maxReadsInProgress.accumulateAndGet(curr, Integer::max); } void untrackReadRequest() { readsInProgress.decrementAndGet(); } int maxReadsInProgressCount() { return maxReadsInProgress.get(); } }
94
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieProtocol.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.proto; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.util.Recycler; import io.netty.util.Recycler.Handle; import io.netty.util.ReferenceCountUtil; import io.netty.util.ReferenceCounted; import org.apache.bookkeeper.proto.BookkeeperProtocol.AuthMessage; /** * The packets of the Bookie protocol all have a 4-byte integer indicating the * type of request or response at the very beginning of the packet followed by a * payload. * */ public interface BookieProtocol { /** * Lowest protocol version which will work with the bookie. */ byte LOWEST_COMPAT_PROTOCOL_VERSION = 0; /** * Current version of the protocol, which client will use. */ byte CURRENT_PROTOCOL_VERSION = 2; /** * Entry Entry ID. To be used when no valid entry id can be assigned. */ long INVALID_ENTRY_ID = -1; /** * Entry identifier representing a request to obtain the last add entry confirmed. */ long LAST_ADD_CONFIRMED = -1; /** * The length of the master key in add packets. This * is fixed at 20 for historic reasons. This is because it * is always generated using the MacDigestManager regardless * of whether Mac is being used for the digest or not */ int MASTER_KEY_LENGTH = 20; /** * The first int of a packet is the header. * It contains the version, opCode and flags. * The initial versions of BK didn't have this structure * and just had an int representing the opCode as the * first int. This handles that case also. */ final class PacketHeader { public static int toInt(byte version, byte opCode, short flags) { if (version == 0) { return (int) opCode; } else { return ((version & 0xFF) << 24) | ((opCode & 0xFF) << 16) | (flags & 0xFFFF); } } public static byte getVersion(int packetHeader) { return (byte) (packetHeader >> 24); } public static byte getOpCode(int packetHeader) { int version = getVersion(packetHeader); if (version == 0) { return (byte) packetHeader; } else { return (byte) ((packetHeader >> 16) & 0xFF); } } public static short getFlags(int packetHeader) { byte version = (byte) (packetHeader >> 24); if (version == 0) { return 0; } else { return (short) (packetHeader & 0xFFFF); } } } /** * The Add entry request payload will be a ledger entry exactly as it should * be logged. The response payload will be a 4-byte integer that has the * error code followed by the 8-byte ledger number and 8-byte entry number * of the entry written. */ byte ADDENTRY = 1; /** * The Read entry request payload will be the ledger number and entry number * to read. (The ledger number is an 8-byte integer and the entry number is * a 8-byte integer.) The response payload will be a 4-byte integer * representing an error code and a ledger entry if the error code is EOK, * otherwise it will be the 8-byte ledger number and the 4-byte entry number * requested. (Note that the first sixteen bytes of the entry happen to be * the ledger number and entry number as well.) */ byte READENTRY = 2; /** * Auth message. This code is for passing auth messages between the auth * providers on the client and bookie. The message payload is determined * by the auth providers themselves. */ byte AUTH = 3; byte READ_LAC = 4; byte WRITE_LAC = 5; byte GET_BOOKIE_INFO = 6; /** * The error code that indicates success. */ int EOK = 0; /** * The error code that indicates that the ledger does not exist. */ int ENOLEDGER = 1; /** * The error code that indicates that the requested entry does not exist. */ int ENOENTRY = 2; /** * The error code that indicates an invalid request type. */ int EBADREQ = 100; /** * General error occurred at the server. */ int EIO = 101; /** * Unauthorized access to ledger. */ int EUA = 102; /** * The server version is incompatible with the client. */ int EBADVERSION = 103; /** * Attempt to write to fenced ledger. */ int EFENCED = 104; /** * The server is running as read-only mode. */ int EREADONLY = 105; /** * Too many concurrent requests. */ int ETOOMANYREQUESTS = 106; /** * Ledger in unknown state. */ int EUNKNOWNLEDGERSTATE = 107; short FLAG_NONE = 0x0; short FLAG_DO_FENCING = 0x0001; short FLAG_RECOVERY_ADD = 0x0002; short FLAG_HIGH_PRIORITY = 0x0004; /** * A Bookie request object. */ class Request { byte protocolVersion; byte opCode; long ledgerId; long entryId; short flags; byte[] masterKey; protected void init(byte protocolVersion, byte opCode, long ledgerId, long entryId, short flags, byte[] masterKey) { this.protocolVersion = protocolVersion; this.opCode = opCode; this.ledgerId = ledgerId; this.entryId = entryId; this.flags = flags; this.masterKey = masterKey; } byte getProtocolVersion() { return protocolVersion; } byte getOpCode() { return opCode; } long getLedgerId() { return ledgerId; } long getEntryId() { return entryId; } short getFlags() { return flags; } boolean hasMasterKey() { return masterKey != null; } byte[] getMasterKey() { assert hasMasterKey(); return masterKey; } boolean isHighPriority() { return (flags & FLAG_HIGH_PRIORITY) == FLAG_HIGH_PRIORITY; } @Override public String toString() { return String.format("Op(%d)[Ledger:%d,Entry:%d]", opCode, ledgerId, entryId); } public void recycle() {} } /** * This is similar to add request, but it used when processing the request on the bookie side. */ class ParsedAddRequest extends Request { ByteBuf data; static ParsedAddRequest create(byte protocolVersion, long ledgerId, long entryId, short flags, byte[] masterKey, ByteBuf data) { ParsedAddRequest add = RECYCLER.get(); add.protocolVersion = protocolVersion; add.opCode = ADDENTRY; add.ledgerId = ledgerId; add.entryId = entryId; add.flags = flags; add.masterKey = masterKey; add.data = data.retain(); return add; } ByteBuf getData() { // We need to have different ByteBufList instances for each bookie write return data; } boolean isRecoveryAdd() { return (flags & FLAG_RECOVERY_ADD) == FLAG_RECOVERY_ADD; } void release() { ReferenceCountUtil.release(data); } private final Handle<ParsedAddRequest> recyclerHandle; private ParsedAddRequest(Handle<ParsedAddRequest> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ParsedAddRequest> RECYCLER = new Recycler<ParsedAddRequest>() { @Override protected ParsedAddRequest newObject(Handle<ParsedAddRequest> handle) { return new ParsedAddRequest(handle); } }; @Override public void recycle() { ledgerId = -1; entryId = -1; masterKey = null; data = null; recyclerHandle.recycle(this); } } /** * A Request that reads data. */ class ReadRequest extends Request { static ReadRequest create(byte protocolVersion, long ledgerId, long entryId, short flags, byte[] masterKey) { ReadRequest read = RECYCLER.get(); read.protocolVersion = protocolVersion; read.opCode = READENTRY; read.ledgerId = ledgerId; read.entryId = entryId; read.flags = flags; read.masterKey = masterKey; return read; } boolean isFencing() { return (flags & FLAG_DO_FENCING) == FLAG_DO_FENCING; } private final Handle<ReadRequest> recyclerHandle; private ReadRequest(Handle<ReadRequest> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<ReadRequest> RECYCLER = new Recycler<ReadRequest>() { @Override protected ReadRequest newObject(Handle<ReadRequest> handle) { return new ReadRequest(handle); } }; @Override public void recycle() { ledgerId = -1; entryId = -1; masterKey = null; recyclerHandle.recycle(this); } } /** * An authentication request. */ class AuthRequest extends Request { final AuthMessage authMessage; AuthRequest(byte protocolVersion, AuthMessage authMessage) { init(protocolVersion, AUTH, -1, -1, FLAG_NONE, null); this.authMessage = authMessage; } AuthMessage getAuthMessage() { return authMessage; } } /** * A response object. */ abstract class Response { byte protocolVersion; byte opCode; int errorCode; long ledgerId; long entryId; protected void init(byte protocolVersion, byte opCode, int errorCode, long ledgerId, long entryId) { this.protocolVersion = protocolVersion; this.opCode = opCode; this.errorCode = errorCode; this.ledgerId = ledgerId; this.entryId = entryId; } byte getProtocolVersion() { return protocolVersion; } byte getOpCode() { return opCode; } long getLedgerId() { return ledgerId; } long getEntryId() { return entryId; } int getErrorCode() { return errorCode; } @Override public String toString() { return String.format("Op(%d)[Ledger:%d,Entry:%d,errorCode=%d]", opCode, ledgerId, entryId, errorCode); } boolean release() { return true; } void recycle() { } } /** * A request that reads data. */ class ReadResponse extends Response implements ReferenceCounted { final ByteBuf data; ReadResponse(byte protocolVersion, int errorCode, long ledgerId, long entryId) { this(protocolVersion, errorCode, ledgerId, entryId, Unpooled.EMPTY_BUFFER); } ReadResponse(byte protocolVersion, int errorCode, long ledgerId, long entryId, ByteBuf data) { init(protocolVersion, READENTRY, errorCode, ledgerId, entryId); this.data = data; } boolean hasData() { return data.readableBytes() > 0; } ByteBuf getData() { return data; } @Override public int refCnt() { return data.refCnt(); } @Override public ReferenceCounted retain() { data.retain(); return this; } @Override public ReferenceCounted retain(int increment) { return data.retain(increment); } @Override public ReferenceCounted touch() { data.touch(); return this; } @Override public ReferenceCounted touch(Object hint) { data.touch(hint); return this; } @Override public boolean release() { return data.release(); } @Override public boolean release(int decrement) { return data.release(decrement); } } /** * A response that adds data. */ class AddResponse extends Response { static AddResponse create(byte protocolVersion, int errorCode, long ledgerId, long entryId) { AddResponse response = RECYCLER.get(); response.init(protocolVersion, ADDENTRY, errorCode, ledgerId, entryId); return response; } private final Handle<AddResponse> recyclerHandle; private AddResponse(Handle<AddResponse> recyclerHandle) { this.recyclerHandle = recyclerHandle; } private static final Recycler<AddResponse> RECYCLER = new Recycler<AddResponse>() { @Override protected AddResponse newObject(Handle<AddResponse> handle) { return new AddResponse(handle); } }; @Override public void recycle() { recyclerHandle.recycle(this); } } /** * An error response. */ class ErrorResponse extends Response { ErrorResponse(byte protocolVersion, byte opCode, int errorCode, long ledgerId, long entryId) { init(protocolVersion, opCode, errorCode, ledgerId, entryId); } } /** * A response with an authentication message. */ class AuthResponse extends Response { final AuthMessage authMessage; AuthResponse(byte protocolVersion, AuthMessage authMessage) { init(protocolVersion, AUTH, EOK, -1, -1); this.authMessage = authMessage; } AuthMessage getAuthMessage() { return authMessage; } } }
95
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/BookieServer.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.proto; import static org.apache.bookkeeper.bookie.BookKeeperServerStats.SERVER_SCOPE; import static org.apache.bookkeeper.conf.AbstractConfiguration.PERMITTED_STARTUP_USERS; import com.google.common.annotations.VisibleForTesting; import io.netty.buffer.ByteBufAllocator; import java.io.IOException; import java.lang.Thread.UncaughtExceptionHandler; import java.net.UnknownHostException; import java.util.Arrays; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieCriticalThread; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.bookie.ExitCode; import org.apache.bookkeeper.bookie.UncleanShutdownDetection; import org.apache.bookkeeper.common.util.JsonUtil.ParseJsonException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.processor.RequestProcessor; import org.apache.bookkeeper.replication.ReplicationException.CompatibilityException; import org.apache.bookkeeper.replication.ReplicationException.UnavailableException; import org.apache.bookkeeper.server.Main; import org.apache.bookkeeper.stats.StatsLogger; import org.apache.bookkeeper.tls.SecurityException; import org.apache.bookkeeper.tls.SecurityHandlerFactory; import org.apache.bookkeeper.tls.SecurityProviderFactoryFactory; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Implements the server-side part of the BookKeeper protocol. * */ public class BookieServer { final ServerConfiguration conf; BookieNettyServer nettyServer; private volatile boolean running = false; private final Bookie bookie; DeathWatcher deathWatcher; UncleanShutdownDetection uncleanShutdownDetection; private static final Logger LOG = LoggerFactory.getLogger(BookieServer.class); int exitCode = ExitCode.OK; // request processor private final RequestProcessor requestProcessor; // Expose Stats private final StatsLogger statsLogger; // Exception handler private volatile UncaughtExceptionHandler uncaughtExceptionHandler = null; public BookieServer(ServerConfiguration conf, Bookie bookie, StatsLogger statsLogger, ByteBufAllocator allocator, UncleanShutdownDetection uncleanShutdownDetection) throws IOException, KeeperException, InterruptedException, BookieException, UnavailableException, CompatibilityException, SecurityException { this.conf = conf; validateUser(conf); String configAsString; try { configAsString = conf.asJson(); LOG.info(configAsString); } catch (ParseJsonException pe) { LOG.error("Got ParseJsonException while converting Config to JSONString", pe); } this.statsLogger = statsLogger; this.bookie = bookie; this.nettyServer = new BookieNettyServer(this.conf, null, allocator); this.uncleanShutdownDetection = uncleanShutdownDetection; final SecurityHandlerFactory shFactory; shFactory = SecurityProviderFactoryFactory .getSecurityProviderFactory(conf.getTLSProviderFactoryClass()); this.requestProcessor = new BookieRequestProcessor(conf, bookie, statsLogger.scope(SERVER_SCOPE), shFactory, allocator, nettyServer.allChannels); this.nettyServer.setRequestProcessor(this.requestProcessor); } /** * 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; } public void start() throws InterruptedException, IOException { this.bookie.start(); // fail fast, when bookie startup is not successful if (!this.bookie.isRunning()) { exitCode = bookie.getExitCode(); this.requestProcessor.close(); return; } this.uncleanShutdownDetection.registerStartUp(); this.nettyServer.start(); running = true; deathWatcher = new DeathWatcher(conf); if (null != uncaughtExceptionHandler) { deathWatcher.setUncaughtExceptionHandler(uncaughtExceptionHandler); } deathWatcher.start(); // fixes test flappers at random places until ISSUE#1400 is resolved // https://github.com/apache/bookkeeper/issues/1400 TimeUnit.MILLISECONDS.sleep(250); } @VisibleForTesting public BookieSocketAddress getLocalAddress() throws UnknownHostException { return BookieImpl.getBookieAddress(conf); } @VisibleForTesting public BookieId getBookieId() throws UnknownHostException { return BookieImpl.getBookieId(conf); } @VisibleForTesting public Bookie getBookie() { return bookie; } @VisibleForTesting public BookieRequestProcessor getBookieRequestProcessor() { return (BookieRequestProcessor) requestProcessor; } /** * Suspend processing of requests in the bookie (for testing). */ @VisibleForTesting public void suspendProcessing() { if (LOG.isDebugEnabled()) { LOG.debug("Suspending bookie server, port is {}", conf.getBookiePort()); } nettyServer.suspendProcessing(); } /** * Resume processing requests in the bookie (for testing). */ @VisibleForTesting public void resumeProcessing() { if (LOG.isDebugEnabled()) { LOG.debug("Resuming bookie server, port is {}", conf.getBookiePort()); } nettyServer.resumeProcessing(); } public synchronized void shutdown() { LOG.info("Shutting down BookieServer"); this.nettyServer.shutdown(); if (!running) { return; } this.requestProcessor.close(); exitCode = bookie.shutdown(); uncleanShutdownDetection.registerCleanShutdown(); running = false; } /** * Ensure the current user can start-up the process if it's restricted. */ private void validateUser(ServerConfiguration conf) throws BookieException { if (conf.containsKey(PERMITTED_STARTUP_USERS)) { String currentUser = System.getProperty("user.name"); String[] propertyValue = conf.getPermittedStartupUsers(); for (String s : propertyValue) { if (s.equals(currentUser)) { return; } } String errorMsg = "System cannot start because current user isn't in permittedStartupUsers." + " Current user: " + currentUser + " permittedStartupUsers: " + Arrays.toString(propertyValue); LOG.error(errorMsg); throw new BookieException.BookieUnauthorizedAccessException(errorMsg); } } public boolean isRunning() { return bookie.isRunning() && nettyServer.isRunning() && running; } /** * Whether bookie is running? * * @return true if bookie is running, otherwise return false */ public boolean isBookieRunning() { return bookie.isRunning(); } public void join() throws InterruptedException { bookie.join(); } public int getExitCode() { return exitCode; } /** * A thread to watch whether bookie and nioserver are still alive. */ private class DeathWatcher extends BookieCriticalThread { private final int watchInterval; DeathWatcher(ServerConfiguration conf) { super("BookieDeathWatcher-" + conf.getBookiePort()); watchInterval = conf.getDeathWatchInterval(); // set a default uncaught exception handler to shutdown the bookie server // when it notices the bookie is not running any more. setUncaughtExceptionHandler((thread, cause) -> { LOG.info("BookieDeathWatcher 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) { // do nothing Thread.currentThread().interrupt(); } if (!isBookieRunning()) { LOG.info("BookieDeathWatcher noticed the bookie is not running any more, exiting the watch loop!"); // death watcher has noticed that bookie 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 "bookie not running" situation. throw new RuntimeException("Bookie is not running any more"); } } } } /** * Legacy Method to run bookie server. */ public static void main(String[] args) { Main.main(args); } @Override public String toString() { String addr = "UNKNOWN"; String id = "?"; try { addr = BookieImpl.getBookieAddress(conf).toString(); id = getBookieId().toString(); } catch (UnknownHostException e) { //Ignored... } return "Bookie Server listening on " + addr + " with id " + id; } }
96
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ForceLedgerProcessorV3.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.proto; import static com.google.common.base.Preconditions.checkArgument; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.BookieImpl; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperProtocol.ForceLedgerRequest; import org.apache.bookkeeper.proto.BookkeeperProtocol.ForceLedgerResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.Response; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.apache.bookkeeper.util.MathUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; class ForceLedgerProcessorV3 extends PacketProcessorBaseV3 implements Runnable { private static final Logger logger = LoggerFactory.getLogger(ForceLedgerProcessorV3.class); public ForceLedgerProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor) { super(request, requestHandler, requestProcessor); } // Returns null if there is no exception thrown private ForceLedgerResponse getForceLedgerResponse() { final long startTimeNanos = MathUtils.nowInNano(); ForceLedgerRequest forceLedgerRequest = request.getForceLedgerRequest(); long ledgerId = forceLedgerRequest.getLedgerId(); final ForceLedgerResponse.Builder forceLedgerResponse = ForceLedgerResponse.newBuilder().setLedgerId(ledgerId); if (!isVersionCompatible()) { forceLedgerResponse.setStatus(StatusCode.EBADVERSION); return forceLedgerResponse.build(); } BookkeeperInternalCallbacks.WriteCallback wcb = (int rc, long ledgerId1, long entryId, BookieId addr, Object ctx) -> { checkArgument(entryId == BookieImpl.METAENTRY_ID_FORCE_LEDGER, "entryId must be METAENTRY_ID_FORCE_LEDGER but was {}", entryId); checkArgument(ledgerId1 == ledgerId, "ledgerId must be {} but was {}", ledgerId, ledgerId1); if (BookieProtocol.EOK == rc) { requestProcessor.getRequestStats().getForceLedgerStats() .registerSuccessfulEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } else { requestProcessor.getRequestStats().getForceLedgerStats() .registerFailedEvent(MathUtils.elapsedNanos(startTimeNanos), TimeUnit.NANOSECONDS); } StatusCode status; switch (rc) { case BookieProtocol.EOK: status = StatusCode.EOK; break; case BookieProtocol.EIO: status = StatusCode.EIO; break; default: status = StatusCode.EUA; break; } forceLedgerResponse.setStatus(status); Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(forceLedgerResponse.getStatus()) .setForceLedgerResponse(forceLedgerResponse); Response resp = response.build(); sendResponse(status, resp, requestProcessor.getRequestStats().getForceLedgerRequestStats()); }; StatusCode status = null; try { requestProcessor.getBookie().forceLedger(ledgerId, wcb, requestHandler); status = StatusCode.EOK; } catch (Throwable t) { logger.error("Unexpected exception while forcing ledger {} : ", ledgerId, t); // some bad request which cause unexpected exception status = StatusCode.EBADREQ; } // If everything is okay, we return null so that the calling function // doesn't return a response back to the caller. if (!status.equals(StatusCode.EOK)) { forceLedgerResponse.setStatus(status); return forceLedgerResponse.build(); } return null; } @Override public void run() { ForceLedgerResponse forceLedgerResponse = getForceLedgerResponse(); if (null != forceLedgerResponse) { Response.Builder response = Response.newBuilder() .setHeader(getHeader()) .setStatus(forceLedgerResponse.getStatus()) .setForceLedgerResponse(forceLedgerResponse); Response resp = response.build(); sendResponse( forceLedgerResponse.getStatus(), resp, requestProcessor.getRequestStats().getForceLedgerRequestStats()); } } /** * this toString method filters out body and masterKey from the output. * masterKey contains the password of the ledger and body is customer data, * so it is not appropriate to have these in logs or system output. */ @Override public String toString() { return RequestUtils.toSafeString(request); } }
97
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/ReadLastConfirmedAndEntryContext.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.proto; import java.util.Optional; import org.apache.bookkeeper.client.LedgerHandle; import org.apache.bookkeeper.net.BookieId; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallbackCtx; /** * A {@link ReadEntryCallbackCtx} for long poll read requests. */ public class ReadLastConfirmedAndEntryContext implements ReadEntryCallbackCtx { final int bookieIndex; final BookieId bookie; long lac = LedgerHandle.INVALID_ENTRY_ID; Optional<Long> lacUpdateTimestamp = Optional.empty(); public ReadLastConfirmedAndEntryContext(int bookieIndex, BookieId bookie) { this.bookieIndex = bookieIndex; this.bookie = bookie; } public int getBookieIndex() { return bookieIndex; } public BookieId getBookieAddress() { return bookie; } @Override public void setLastAddConfirmed(long lac) { this.lac = lac; } @Override public long getLastAddConfirmed() { return lac; } public Optional<Long> getLacUpdateTimestamp() { return lacUpdateTimestamp; } public void setLacUpdateTimestamp(long lacUpdateTimestamp) { this.lacUpdateTimestamp = Optional.of(lacUpdateTimestamp); } }
98
0
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper
Create_ds/bookkeeper/bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/LongPollReadEntryProcessorV3.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.proto; import com.google.common.base.Stopwatch; import io.netty.util.HashedWheelTimer; import io.netty.util.Timeout; import java.io.IOException; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.bookie.BookieException; import org.apache.bookkeeper.bookie.LastAddConfirmedUpdateNotification; import org.apache.bookkeeper.common.util.Watcher; import org.apache.bookkeeper.proto.BookkeeperProtocol.ReadResponse; import org.apache.bookkeeper.proto.BookkeeperProtocol.Request; import org.apache.bookkeeper.proto.BookkeeperProtocol.StatusCode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Processor handling long poll read entry request. */ class LongPollReadEntryProcessorV3 extends ReadEntryProcessorV3 implements Watcher<LastAddConfirmedUpdateNotification> { private static final Logger logger = LoggerFactory.getLogger(LongPollReadEntryProcessorV3.class); private final Long previousLAC; private Optional<Long> lastAddConfirmedUpdateTime = Optional.empty(); // long poll execution state private final ExecutorService longPollThreadPool; private final HashedWheelTimer requestTimer; private Timeout expirationTimerTask = null; private Future<?> deferredTask = null; private boolean shouldReadEntry = false; LongPollReadEntryProcessorV3(Request request, BookieRequestHandler requestHandler, BookieRequestProcessor requestProcessor, ExecutorService fenceThreadPool, ExecutorService longPollThreadPool, HashedWheelTimer requestTimer) { super(request, requestHandler, requestProcessor, fenceThreadPool); this.previousLAC = readRequest.getPreviousLAC(); this.longPollThreadPool = longPollThreadPool; this.requestTimer = requestTimer; } @Override protected Long getPreviousLAC() { return previousLAC; } private synchronized boolean shouldReadEntry() { return shouldReadEntry; } @Override protected ReadResponse readEntry(ReadResponse.Builder readResponseBuilder, long entryId, Stopwatch startTimeSw) throws IOException, BookieException { if (RequestUtils.shouldPiggybackEntry(readRequest)) { if (!readRequest.hasPreviousLAC() || (BookieProtocol.LAST_ADD_CONFIRMED != entryId)) { // This is not a valid request - client bug? logger.error("Incorrect read request, entry piggyback requested incorrectly for ledgerId {} entryId {}", ledgerId, entryId); return buildResponse(readResponseBuilder, StatusCode.EBADREQ, startTimeSw); } else { long knownLAC = requestProcessor.bookie.readLastAddConfirmed(ledgerId); readResponseBuilder.setMaxLAC(knownLAC); if (knownLAC > previousLAC) { entryId = previousLAC + 1; readResponseBuilder.setMaxLAC(knownLAC); if (lastAddConfirmedUpdateTime.isPresent()) { readResponseBuilder.setLacUpdateTimestamp(lastAddConfirmedUpdateTime.get()); } if (logger.isDebugEnabled()) { logger.debug("ReadLAC Piggy Back reading entry:{} from ledger: {}", entryId, ledgerId); } try { return super.readEntry(readResponseBuilder, entryId, true, startTimeSw); } catch (Bookie.NoEntryException e) { requestProcessor.getRequestStats().getReadLastEntryNoEntryErrorCounter().inc(); logger.info( "No entry found while piggyback reading entry {} from ledger {} : previous lac = {}", entryId, ledgerId, previousLAC); // piggy back is best effort and this request can fail genuinely because of striping // entries across the ensemble return buildResponse(readResponseBuilder, StatusCode.EOK, startTimeSw); } } else { if (knownLAC < previousLAC) { if (logger.isDebugEnabled()) { logger.debug("Found smaller lac when piggy back reading lac and entry from ledger {} :" + " previous lac = {}, known lac = {}", ledgerId, previousLAC, knownLAC); } } return buildResponse(readResponseBuilder, StatusCode.EOK, startTimeSw); } } } else { return super.readEntry(readResponseBuilder, entryId, false, startTimeSw); } } private ReadResponse buildErrorResponse(StatusCode statusCode, Stopwatch sw) { ReadResponse.Builder builder = ReadResponse.newBuilder() .setLedgerId(ledgerId) .setEntryId(entryId); return buildResponse(builder, statusCode, sw); } private ReadResponse getLongPollReadResponse() { if (!shouldReadEntry() && readRequest.hasTimeOut()) { if (logger.isTraceEnabled()) { logger.trace("Waiting For LAC Update {}", previousLAC); } final Stopwatch startTimeSw = Stopwatch.createStarted(); final boolean watched; try { watched = requestProcessor.getBookie().waitForLastAddConfirmedUpdate(ledgerId, previousLAC, this); } catch (Bookie.NoLedgerException e) { logger.info("No ledger found while longpoll reading ledger {}, previous lac = {}.", ledgerId, previousLAC); return buildErrorResponse(StatusCode.ENOLEDGER, startTimeSw); } catch (IOException ioe) { logger.error("IOException while longpoll reading ledger {}, previous lac = {} : ", ledgerId, previousLAC, ioe); return buildErrorResponse(StatusCode.EIO, startTimeSw); } registerSuccessfulEvent(requestProcessor.getRequestStats().getLongPollPreWaitStats(), startTimeSw); lastPhaseStartTime.reset().start(); if (watched) { // successfully registered watcher to lac updates if (logger.isTraceEnabled()) { logger.trace("Waiting For LAC Update {}: Timeout {}", previousLAC, readRequest.getTimeOut()); } synchronized (this) { expirationTimerTask = requestTimer.newTimeout(timeout -> { requestProcessor.getBookie().cancelWaitForLastAddConfirmedUpdate(ledgerId, this); // When the timeout expires just get whatever is the current // readLastConfirmed LongPollReadEntryProcessorV3.this.scheduleDeferredRead(true); }, readRequest.getTimeOut(), TimeUnit.MILLISECONDS); } return null; } } // request doesn't have timeout or fail to wait, proceed to read entry return getReadResponse(); } @Override protected void executeOp() { ReadResponse readResponse = getLongPollReadResponse(); if (null != readResponse) { sendResponse(readResponse); } } @Override public void update(LastAddConfirmedUpdateNotification newLACNotification) { if (newLACNotification.getLastAddConfirmed() > previousLAC) { if (newLACNotification.getLastAddConfirmed() != Long.MAX_VALUE && !lastAddConfirmedUpdateTime.isPresent()) { lastAddConfirmedUpdateTime = Optional.of(newLACNotification.getTimestamp()); } if (logger.isTraceEnabled()) { logger.trace("Last Add Confirmed Advanced to {} for request {}", newLACNotification.getLastAddConfirmed(), request); } scheduleDeferredRead(false); } newLACNotification.recycle(); } private synchronized void scheduleDeferredRead(boolean timeout) { if (null == deferredTask) { if (logger.isTraceEnabled()) { logger.trace("Deferred Task, expired: {}, request: {}", timeout, request); } try { shouldReadEntry = true; deferredTask = longPollThreadPool.submit(this); } catch (RejectedExecutionException exc) { // If the threadPool has been shutdown, simply drop the task } if (null != expirationTimerTask) { expirationTimerTask.cancel(); } registerEvent(timeout, requestProcessor.getRequestStats().getLongPollWaitStats(), lastPhaseStartTime); lastPhaseStartTime.reset().start(); } } }
99