Search in sources :

Example 31 with Versioned

use of org.apache.bookkeeper.versioning.Versioned in project bookkeeper by apache.

the class Utils method zkGetData.

/**
 * Retrieve data from zookeeper <code>path</code>.
 *
 * @param path
 *          zookeeper path to retrieve data
 * @param watch
 *          whether to watch the path
 * @return future representing the versioned value. null version or null value means path doesn't exist.
 */
public static CompletableFuture<Versioned<byte[]>> zkGetData(ZooKeeper zk, String path, boolean watch) {
    final CompletableFuture<Versioned<byte[]>> promise = new CompletableFuture<Versioned<byte[]>>();
    zk.getData(path, watch, new AsyncCallback.DataCallback() {

        @Override
        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
            if (KeeperException.Code.OK.intValue() == rc) {
                if (null == stat) {
                    promise.complete(new Versioned<byte[]>(null, null));
                } else {
                    promise.complete(new Versioned<byte[]>(data, new LongVersion(stat.getVersion())));
                }
            } else if (KeeperException.Code.NONODE.intValue() == rc) {
                promise.complete(new Versioned<byte[]>(null, null));
            } else {
                promise.completeExceptionally(KeeperException.create(KeeperException.Code.get(rc)));
            }
        }
    }, null);
    return promise;
}
Also used : Versioned(org.apache.bookkeeper.versioning.Versioned) AsyncCallback(org.apache.zookeeper.AsyncCallback) CompletableFuture(java.util.concurrent.CompletableFuture) Stat(org.apache.zookeeper.data.Stat) LongVersion(org.apache.bookkeeper.versioning.LongVersion)

Example 32 with Versioned

use of org.apache.bookkeeper.versioning.Versioned in project bookkeeper by apache.

the class ZKLogStreamMetadataStore method renameLogMetadata.

private CompletableFuture<Void> renameLogMetadata(URI uri, LogMetadataForWriter oldMetadata, String newStreamName) {
    final LinkedList<Op> createOps = Lists.newLinkedList();
    final LinkedList<Op> deleteOps = Lists.newLinkedList();
    List<ACL> acls = zooKeeperClient.getDefaultACL();
    // get the root path
    String oldRootPath = oldMetadata.getLogRootPath();
    String newRootPath = LogMetadata.getLogRootPath(uri, newStreamName, conf.getUnpartitionedStreamName());
    // 0. the log path
    deleteOps.addFirst(Op.delete(LogMetadata.getLogStreamPath(uri, oldMetadata.getLogName()), -1));
    // 1. the root path
    createOps.addLast(Op.create(newRootPath, EMPTY_BYTES, acls, CreateMode.PERSISTENT));
    deleteOps.addFirst(Op.delete(oldRootPath, -1));
    // 2. max id
    Versioned<byte[]> maxTxIdData = oldMetadata.getMaxTxIdData();
    deleteOldPathAndCreateNewPath(oldRootPath, MAX_TXID_PATH, maxTxIdData, newRootPath, DLUtils.serializeTransactionId(0L), acls, createOps, deleteOps);
    // 3. version
    createOps.addLast(Op.create(newRootPath + VERSION_PATH, intToBytes(LAYOUT_VERSION), acls, CreateMode.PERSISTENT));
    deleteOps.addFirst(Op.delete(oldRootPath + VERSION_PATH, -1));
    // 4. lock path (NOTE: if the stream is locked by a writer, then the delete will fail as you can not
    // delete the lock path if children is not empty.
    createOps.addLast(Op.create(newRootPath + LOCK_PATH, EMPTY_BYTES, acls, CreateMode.PERSISTENT));
    deleteOps.addFirst(Op.delete(oldRootPath + LOCK_PATH, -1));
    // 5. read lock path (NOTE: same reason as the write lock)
    createOps.addLast(Op.create(newRootPath + READ_LOCK_PATH, EMPTY_BYTES, acls, CreateMode.PERSISTENT));
    deleteOps.addFirst(Op.delete(oldRootPath + READ_LOCK_PATH, -1));
    // 6. allocation path
    Versioned<byte[]> allocationData = oldMetadata.getAllocationData();
    deleteOldPathAndCreateNewPath(oldRootPath, ALLOCATION_PATH, allocationData, newRootPath, EMPTY_BYTES, acls, createOps, deleteOps);
    // 7. log segments
    Versioned<byte[]> maxLSSNData = oldMetadata.getMaxLSSNData();
    deleteOldPathAndCreateNewPath(oldRootPath, LOGSEGMENTS_PATH, maxLSSNData, newRootPath, DLUtils.serializeLogSegmentSequenceNumber(UNASSIGNED_LOGSEGMENT_SEQNO), acls, createOps, deleteOps);
    // 8. copy the log segments
    CompletableFuture<List<LogSegmentMetadata>> segmentsFuture;
    if (pathExists(maxLSSNData)) {
        segmentsFuture = getLogSegments(zooKeeperClient, oldRootPath + LOGSEGMENTS_PATH);
    } else {
        segmentsFuture = FutureUtils.value(Collections.emptyList());
    }
    return segmentsFuture.thenApply(segments -> {
        for (LogSegmentMetadata segment : segments) {
            deleteOldSegmentAndCreateNewSegment(segment, newRootPath + LOGSEGMENTS_PATH, acls, createOps, deleteOps);
        }
        return null;
    }).thenCompose(ignored -> getMissingPaths(zooKeeperClient, uri, newStreamName)).thenCompose(paths -> {
        for (String path : paths) {
            createOps.addFirst(Op.create(path, EMPTY_BYTES, acls, CreateMode.PERSISTENT));
        }
        return executeRenameTxn(oldRootPath, newRootPath, createOps, deleteOps);
    });
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) LogExistsException(org.apache.distributedlog.exceptions.LogExistsException) ZKDistributedLock(org.apache.distributedlog.lock.ZKDistributedLock) LogSegmentMetadataStore(org.apache.distributedlog.logsegment.LogSegmentMetadataStore) LoggerFactory(org.slf4j.LoggerFactory) PermitManager(org.apache.distributedlog.common.util.PermitManager) LogMetadataForReader(org.apache.distributedlog.metadata.LogMetadataForReader) Stat(org.apache.zookeeper.data.Stat) LogNotFoundException(org.apache.distributedlog.exceptions.LogNotFoundException) LOGSEGMENTS_PATH(org.apache.distributedlog.metadata.LogMetadata.LOGSEGMENTS_PATH) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) UnexpectedException(org.apache.distributedlog.exceptions.UnexpectedException) READ_LOCK_PATH(org.apache.distributedlog.metadata.LogMetadata.READ_LOCK_PATH) SchedulerUtils(org.apache.distributedlog.common.util.SchedulerUtils) Transaction(org.apache.distributedlog.util.Transaction) URI(java.net.URI) DistributedLogConstants(org.apache.distributedlog.DistributedLogConstants) ZKUtil(org.apache.zookeeper.ZKUtil) ZKException(org.apache.distributedlog.exceptions.ZKException) ZooKeeper(org.apache.zookeeper.ZooKeeper) Op(org.apache.zookeeper.Op) OrderedScheduler(org.apache.bookkeeper.common.util.OrderedScheduler) CancellationException(java.util.concurrent.CancellationException) FutureUtils(org.apache.bookkeeper.common.concurrent.FutureUtils) Create(org.apache.zookeeper.Op.Create) List(java.util.List) LockCancelledException(org.apache.distributedlog.exceptions.LockCancelledException) StatsLogger(org.apache.bookkeeper.stats.StatsLogger) Optional(java.util.Optional) ZKLogSegmentMetadataStore(org.apache.distributedlog.impl.ZKLogSegmentMetadataStore) EMPTY_BYTES(org.apache.distributedlog.DistributedLogConstants.EMPTY_BYTES) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) Code(org.apache.zookeeper.KeeperException.Code) LongVersion(org.apache.bookkeeper.versioning.LongVersion) DLInterruptedException(org.apache.distributedlog.exceptions.DLInterruptedException) LockingException(org.apache.distributedlog.exceptions.LockingException) CompletableFuture(java.util.concurrent.CompletableFuture) ACL(org.apache.zookeeper.data.ACL) LOCK_PATH(org.apache.distributedlog.metadata.LogMetadata.LOCK_PATH) ZooKeeperConnectionException(org.apache.distributedlog.ZooKeeperClient.ZooKeeperConnectionException) Lists(com.google.common.collect.Lists) LogSegmentMetadata(org.apache.distributedlog.LogSegmentMetadata) DistributedLogConfiguration(org.apache.distributedlog.DistributedLogConfiguration) Versioned(org.apache.bookkeeper.versioning.Versioned) Utils(org.apache.distributedlog.util.Utils) LimitedPermitManager(org.apache.distributedlog.zk.LimitedPermitManager) ZKTransaction(org.apache.distributedlog.zk.ZKTransaction) OpResult(org.apache.zookeeper.OpResult) LinkedList(java.util.LinkedList) LogStreamMetadataStore(org.apache.distributedlog.metadata.LogStreamMetadataStore) Delete(org.apache.zookeeper.Op.Delete) Logger(org.slf4j.Logger) LAYOUT_VERSION(org.apache.distributedlog.metadata.LogMetadata.LAYOUT_VERSION) FutureEventListener(org.apache.bookkeeper.common.concurrent.FutureEventListener) KeeperException(org.apache.zookeeper.KeeperException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ALLOCATION_PATH(org.apache.distributedlog.metadata.LogMetadata.ALLOCATION_PATH) IOException(java.io.IOException) MAX_TXID_PATH(org.apache.distributedlog.metadata.LogMetadata.MAX_TXID_PATH) LogMetadata(org.apache.distributedlog.metadata.LogMetadata) TimeUnit(java.util.concurrent.TimeUnit) DLUtils(org.apache.distributedlog.util.DLUtils) DistributedLock(org.apache.distributedlog.lock.DistributedLock) PathUtils(org.apache.zookeeper.common.PathUtils) LogMetadataForWriter(org.apache.distributedlog.metadata.LogMetadataForWriter) AsyncCallback(org.apache.zookeeper.AsyncCallback) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ZKSessionLockFactory(org.apache.distributedlog.lock.ZKSessionLockFactory) UNASSIGNED_LOGSEGMENT_SEQNO(org.apache.distributedlog.DistributedLogConstants.UNASSIGNED_LOGSEGMENT_SEQNO) Collections(java.util.Collections) InvalidStreamNameException(org.apache.distributedlog.exceptions.InvalidStreamNameException) VERSION_PATH(org.apache.distributedlog.metadata.LogMetadata.VERSION_PATH) ZooKeeperClient(org.apache.distributedlog.ZooKeeperClient) SessionLockFactory(org.apache.distributedlog.lock.SessionLockFactory) Op(org.apache.zookeeper.Op) LogSegmentMetadata(org.apache.distributedlog.LogSegmentMetadata) ACL(org.apache.zookeeper.data.ACL) List(java.util.List) LinkedList(java.util.LinkedList)

Example 33 with Versioned

use of org.apache.bookkeeper.versioning.Versioned in project bookkeeper by apache.

the class ZKLogStreamMetadataStore method executeCreateMissingPathTxn.

private static void executeCreateMissingPathTxn(ZooKeeper zk, List<Op> zkOps, List<byte[]> pathsToCreate, List<Versioned<byte[]>> metadatas, String logRootPath, CompletableFuture<List<Versioned<byte[]>>> promise) {
    zk.multi(zkOps, new AsyncCallback.MultiCallback() {

        @Override
        public void processResult(int rc, String path, Object ctx, List<OpResult> resultList) {
            if (KeeperException.Code.OK.intValue() == rc) {
                List<Versioned<byte[]>> finalMetadatas = Lists.newArrayListWithExpectedSize(metadatas.size());
                for (int i = 0; i < pathsToCreate.size(); i++) {
                    byte[] dataCreated = pathsToCreate.get(i);
                    if (null == dataCreated) {
                        finalMetadatas.add(metadatas.get(i));
                    } else {
                        finalMetadatas.add(new Versioned<byte[]>(dataCreated, new LongVersion(0)));
                    }
                }
                promise.complete(finalMetadatas);
            } else if (KeeperException.Code.NODEEXISTS.intValue() == rc) {
                promise.completeExceptionally(new LogExistsException("Someone just created log " + logRootPath));
            } else {
                if (LOG.isDebugEnabled()) {
                    StringBuilder builder = new StringBuilder();
                    for (OpResult result : resultList) {
                        if (result instanceof OpResult.ErrorResult) {
                            OpResult.ErrorResult errorResult = (OpResult.ErrorResult) result;
                            builder.append(errorResult.getErr()).append(",");
                        } else {
                            builder.append(0).append(",");
                        }
                    }
                    String resultCodeList = builder.substring(0, builder.length() - 1);
                    LOG.debug("Failed to create log, full rc list = {}", resultCodeList);
                }
                promise.completeExceptionally(new ZKException("Failed to create log " + logRootPath, KeeperException.Code.get(rc)));
            }
        }
    }, null);
}
Also used : LogExistsException(org.apache.distributedlog.exceptions.LogExistsException) Versioned(org.apache.bookkeeper.versioning.Versioned) AsyncCallback(org.apache.zookeeper.AsyncCallback) ZKException(org.apache.distributedlog.exceptions.ZKException) OpResult(org.apache.zookeeper.OpResult) LongVersion(org.apache.bookkeeper.versioning.LongVersion) List(java.util.List) LinkedList(java.util.LinkedList)

Example 34 with Versioned

use of org.apache.bookkeeper.versioning.Versioned in project bookkeeper by apache.

the class ListBookiesCommandTest method testListEmptyBookies.

@Test
public void testListEmptyBookies() throws Exception {
    // overwrite regClient to return empty bookies
    when(regClient.getWritableBookies()).thenReturn(value(new Versioned<>(Collections.emptySet(), new LongVersion(0L))));
    when(regClient.getReadOnlyBookies()).thenReturn(value(new Versioned<>(Collections.emptySet(), new LongVersion(0L))));
    ListBookiesCommand cmd = new ListBookiesCommand();
    assertTrue(cmd.apply(bkFlags, new String[] { "-rw" }));
    getMockedStatic(CommandHelpers.class).verify(() -> CommandHelpers.getBookieSocketAddrStringRepresentation(any(), any()), times(0));
    assertTrue(cmd.apply(bkFlags, new String[] { "-ro" }));
    getMockedStatic(CommandHelpers.class).verify(() -> CommandHelpers.getBookieSocketAddrStringRepresentation(any(), any()), times(0));
}
Also used : Versioned(org.apache.bookkeeper.versioning.Versioned) LongVersion(org.apache.bookkeeper.versioning.LongVersion) CommandHelpers(org.apache.bookkeeper.tools.cli.helpers.CommandHelpers) Test(org.junit.Test)

Example 35 with Versioned

use of org.apache.bookkeeper.versioning.Versioned in project bookkeeper by apache.

the class ListBookiesCommandTest method setup.

@Before
public void setup() throws Exception {
    super.setup();
    writableBookies = createBookies(3181, 10);
    readonlyBookies = createBookies(4181, 10);
    allBookies = new HashSet<>();
    allBookies.addAll(writableBookies);
    allBookies.addAll(readonlyBookies);
    when(regClient.getWritableBookies()).thenReturn(value(new Versioned<>(writableBookies, new LongVersion(0L))));
    when(regClient.getBookieServiceInfo(any(BookieId.class))).thenReturn(value(new Versioned<>(BookieServiceInfoUtils.buildLegacyBookieServiceInfo("localhost:1234"), new LongVersion(0))));
    when(regClient.getReadOnlyBookies()).thenReturn(value(new Versioned<>(readonlyBookies, new LongVersion(0L))));
    when(regClient.getAllBookies()).thenReturn(value(new Versioned<>(allBookies, new LongVersion(0L))));
    mockStatic(CommandHelpers.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
}
Also used : BookieId(org.apache.bookkeeper.net.BookieId) Versioned(org.apache.bookkeeper.versioning.Versioned) LongVersion(org.apache.bookkeeper.versioning.LongVersion) Before(org.junit.Before)

Aggregations

Versioned (org.apache.bookkeeper.versioning.Versioned)135 LongVersion (org.apache.bookkeeper.versioning.LongVersion)72 Test (org.junit.Test)70 CompletableFuture (java.util.concurrent.CompletableFuture)51 LedgerMetadata (org.apache.bookkeeper.client.api.LedgerMetadata)42 Version (org.apache.bookkeeper.versioning.Version)36 List (java.util.List)35 BookieId (org.apache.bookkeeper.net.BookieId)35 Stat (org.apache.zookeeper.data.Stat)33 LedgerManager (org.apache.bookkeeper.meta.LedgerManager)28 Set (java.util.Set)26 IOException (java.io.IOException)23 BKException (org.apache.bookkeeper.client.BKException)23 HashSet (java.util.HashSet)22 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)21 ZkVersion (org.apache.bookkeeper.meta.ZkVersion)21 Lists (com.google.common.collect.Lists)20 Slf4j (lombok.extern.slf4j.Slf4j)20 URI (java.net.URI)19 Logger (org.slf4j.Logger)17