Search in sources :

Example 16 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by yahoo.

the class ManagedLedgerFactoryShutdownTest method setup.

@BeforeMethod
private void setup() {
    final long version = 0;
    final long createTimeMillis = System.currentTimeMillis();
    metadataStore = mock(MetadataStoreExtended.class);
    bookKeeper = mock(BookKeeper.class);
    given(metadataStore.get(any())).willAnswer(inv -> {
        String path = inv.getArgument(0, String.class);
        if (path == null) {
            throw new IllegalArgumentException("Path is null.");
        }
        if (path.endsWith(ledgerName)) {
            // ledger
            MLDataFormats.ManagedLedgerInfo.Builder mli = MLDataFormats.ManagedLedgerInfo.newBuilder().addLedgerInfo(0, MLDataFormats.ManagedLedgerInfo.LedgerInfo.newBuilder().setLedgerId(0).setEntries(0).setTimestamp(System.currentTimeMillis()));
            Stat stat = new Stat(path, version, createTimeMillis, createTimeMillis, false, false);
            return CompletableFuture.supplyAsync(() -> {
                try {
                    slowZk.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MLDataFormats.ManagedLedgerInfo managedLedgerInfo = mli.build();
                log.info("metadataStore.get({}) returned,managedLedgerInfo={},stat={}", path, managedLedgerInfo, stat);
                return Optional.of(new GetResult(managedLedgerInfo.toByteArray(), stat));
            });
        } else if (path.contains(ledgerName)) {
            // cursor
            MLDataFormats.ManagedCursorInfo.Builder mci = MLDataFormats.ManagedCursorInfo.newBuilder().setCursorsLedgerId(-1).setMarkDeleteLedgerId(0).setMarkDeleteLedgerId(-1);
            Stat stat = new Stat(path, version, createTimeMillis, createTimeMillis, false, false);
            return CompletableFuture.supplyAsync(() -> {
                try {
                    slowZk.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MLDataFormats.ManagedCursorInfo managedCursorInfo = mci.build();
                log.info("metadataStore.get({}) returned:managedCursorInfo={},stat={}", path, managedCursorInfo, stat);
                return Optional.of(new GetResult(managedCursorInfo.toByteArray(), stat));
            });
        } else {
            throw new IllegalArgumentException("Invalid path: " + path);
        }
    });
    given(metadataStore.put(anyString(), any(), any())).willAnswer(inv -> {
        @SuppressWarnings("unchecked cast") Optional<Long> expectedVersion = inv.getArgument(2, Optional.class);
        return CompletableFuture.supplyAsync(() -> new Stat(inv.getArgument(0, String.class), expectedVersion.orElse(0L) + 1, createTimeMillis, System.currentTimeMillis(), false, false));
    });
    given(metadataStore.getChildren(anyString())).willAnswer(inv -> CompletableFuture.supplyAsync(() -> Collections.singletonList("cursor")));
    LedgerHandle ledgerHandle = mock(LedgerHandle.class);
    LedgerHandle newLedgerHandle = mock(LedgerHandle.class);
    OrderedExecutor executor = OrderedExecutor.newBuilder().name("Test").build();
    given(bookKeeper.getMainWorkerPool()).willReturn(executor);
    doAnswer(inv -> {
        AsyncCallback.OpenCallback cb = inv.getArgument(3, AsyncCallback.OpenCallback.class);
        cb.openComplete(0, ledgerHandle, inv.getArgument(4, Object.class));
        return null;
    }).when(bookKeeper).asyncOpenLedger(anyLong(), any(), any(), any(), any());
    doAnswer(inv -> {
        AsyncCallback.CreateCallback cb = inv.getArgument(5, AsyncCallback.CreateCallback.class);
        cb.createComplete(0, newLedgerHandle, inv.getArgument(6, Object.class));
        return null;
    }).when(bookKeeper).asyncCreateLedger(anyInt(), anyInt(), anyInt(), any(), any(), any(), /*callback*/
    any(), any());
}
Also used : GetResult(org.apache.pulsar.metadata.api.GetResult) LedgerHandle(org.apache.bookkeeper.client.LedgerHandle) AsyncCallback(org.apache.bookkeeper.client.AsyncCallback) BookKeeper(org.apache.bookkeeper.client.BookKeeper) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) OrderedExecutor(org.apache.bookkeeper.common.util.OrderedExecutor) Stat(org.apache.pulsar.metadata.api.Stat) MLDataFormats(org.apache.bookkeeper.mledger.proto.MLDataFormats) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) BeforeMethod(org.testng.annotations.BeforeMethod)

Example 17 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by yahoo.

the class RocksdbMetadataStore method storeGet.

@Override
public CompletableFuture<Optional<GetResult>> storeGet(String path) {
    if (log.isDebugEnabled()) {
        log.debug("getFromStore.path={},instanceId={}", path, instanceId);
    }
    try {
        dbStateLock.readLock().lock();
        if (state == State.CLOSED) {
            throw new MetadataStoreException.AlreadyClosedException("");
        }
        byte[] value = db.get(optionCache, toBytes(path));
        if (value == null) {
            return CompletableFuture.completedFuture(Optional.empty());
        }
        MetaValue metaValue = MetaValue.parse(value);
        if (metaValue.ephemeral && metaValue.owner != instanceId) {
            delete(path, Optional.empty());
            return CompletableFuture.completedFuture(Optional.empty());
        }
        GetResult result = new GetResult(metaValue.getData(), new Stat(path, metaValue.getVersion(), metaValue.getCreatedTimestamp(), metaValue.getModifiedTimestamp(), metaValue.ephemeral, metaValue.getOwner() == instanceId));
        return CompletableFuture.completedFuture(Optional.of(result));
    } catch (Throwable e) {
        return FutureUtil.failedFuture(MetadataStoreException.wrap(e));
    } finally {
        dbStateLock.readLock().unlock();
    }
}
Also used : Stat(org.apache.pulsar.metadata.api.Stat) GetResult(org.apache.pulsar.metadata.api.GetResult)

Example 18 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by yahoo.

the class ZKMetadataStore method handleGetResult.

private void handleGetResult(OpGet op, OpResult opr) {
    if (opr instanceof OpResult.ErrorResult) {
        OpResult.ErrorResult er = (OpResult.ErrorResult) opr;
        Code code = Code.get(er.getErr());
        if (code == Code.NONODE) {
            // For get operations, we return an empty optional
            op.getFuture().complete(Optional.empty());
        } else {
            op.getFuture().completeExceptionally(getException(code, op.getPath()));
        }
    } else {
        OpResult.GetDataResult gdr = (OpResult.GetDataResult) opr;
        op.getFuture().complete(Optional.of(new GetResult(gdr.getData(), getStat(op.getPath(), gdr.getStat()))));
    }
}
Also used : GetResult(org.apache.pulsar.metadata.api.GetResult) OpResult(org.apache.zookeeper.OpResult) Code(org.apache.zookeeper.KeeperException.Code)

Example 19 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by yahoo.

the class ResourceLockImpl method doRevalidate.

private synchronized CompletableFuture<Void> doRevalidate(T newValue) {
    if (log.isDebugEnabled()) {
        log.debug("doRevalidate with newValue={}, version={}", newValue, version);
    }
    return store.get(path).thenCompose(optGetResult -> {
        if (!optGetResult.isPresent()) {
            // The lock just disappeared, try to acquire it again
            // Reset the expectation on the version
            setVersion(-1L);
            return acquireWithNoRevalidation(newValue).thenRun(() -> log.info("Successfully re-acquired missing lock at {}", path));
        }
        GetResult res = optGetResult.get();
        if (!res.getStat().isEphemeral()) {
            return FutureUtils.exception(new LockBusyException("Path " + path + " is already created as non-ephemeral"));
        }
        T existingValue;
        try {
            existingValue = serde.deserialize(path, res.getValue(), res.getStat());
        } catch (Throwable t) {
            return FutureUtils.exception(t);
        }
        synchronized (ResourceLockImpl.this) {
            if (newValue.equals(existingValue)) {
                if (res.getStat().isCreatedBySelf()) {
                    // If the new lock belongs to the same session, there's no
                    // need to recreate it.
                    version = res.getStat().getVersion();
                    value = newValue;
                    return CompletableFuture.completedFuture(null);
                } else {
                    // The lock needs to get recreated since it belong to an earlier
                    // session which maybe expiring soon
                    log.info("Deleting stale lock at {}", path);
                    return store.delete(path, Optional.of(res.getStat().getVersion())).thenRun(() -> setVersion(-1L)).thenCompose(__ -> acquireWithNoRevalidation(newValue)).thenRun(() -> log.info("Successfully re-acquired stale lock at {}", path));
                }
            }
            if (!res.getStat().isCreatedBySelf()) {
                return FutureUtils.exception(new LockBusyException("Resource at " + path + " is already locked"));
            }
            return store.delete(path, Optional.of(res.getStat().getVersion())).thenRun(() -> setVersion(-1L)).thenCompose(__ -> acquireWithNoRevalidation(newValue)).thenRun(() -> log.info("Successfully re-acquired lock at {}", path));
        }
    });
}
Also used : MetadataStoreException(org.apache.pulsar.metadata.api.MetadataStoreException) LockBusyException(org.apache.pulsar.metadata.api.MetadataStoreException.LockBusyException) CreateOption(org.apache.pulsar.metadata.api.extended.CreateOption) CompletableFuture(java.util.concurrent.CompletableFuture) MetadataStoreExtended(org.apache.pulsar.metadata.api.extended.MetadataStoreExtended) FutureUtils(org.apache.bookkeeper.common.concurrent.FutureUtils) Slf4j(lombok.extern.slf4j.Slf4j) GetResult(org.apache.pulsar.metadata.api.GetResult) MetadataSerde(org.apache.pulsar.metadata.api.MetadataSerde) ResourceLock(org.apache.pulsar.metadata.api.coordination.ResourceLock) BadVersionException(org.apache.pulsar.metadata.api.MetadataStoreException.BadVersionException) Optional(java.util.Optional) EnumSet(java.util.EnumSet) GetResult(org.apache.pulsar.metadata.api.GetResult) LockBusyException(org.apache.pulsar.metadata.api.MetadataStoreException.LockBusyException)

Example 20 with GetResult

use of org.apache.pulsar.metadata.api.GetResult in project pulsar by yahoo.

the class PulsarLedgerUnderreplicationManager method getLedgerUnreplicationInfo.

@Override
public UnderreplicatedLedger getLedgerUnreplicationInfo(long ledgerId) throws ReplicationException.UnavailableException {
    try {
        String path = getUrLedgerPath(ledgerId);
        Optional<GetResult> optRes = store.get(path).get();
        if (!optRes.isPresent()) {
            if (log.isDebugEnabled()) {
                log.debug("Ledger: {} is not marked underreplicated", ledgerId);
            }
            return null;
        }
        byte[] data = optRes.get().getValue();
        UnderreplicatedLedgerFormat.Builder builder = UnderreplicatedLedgerFormat.newBuilder();
        TextFormat.merge(new String(data, UTF_8), builder);
        UnderreplicatedLedgerFormat underreplicatedLedgerFormat = builder.build();
        PulsarUnderreplicatedLedger underreplicatedLedger = new PulsarUnderreplicatedLedger(ledgerId);
        List<String> replicaList = underreplicatedLedgerFormat.getReplicaList();
        long ctime = (underreplicatedLedgerFormat.hasCtime() ? underreplicatedLedgerFormat.getCtime() : UnderreplicatedLedger.UNASSIGNED_CTIME);
        underreplicatedLedger.setCtime(ctime);
        underreplicatedLedger.setReplicaList(replicaList);
        return underreplicatedLedger;
    } catch (ExecutionException ee) {
        throw new ReplicationException.UnavailableException("Error contacting with metadata store", ee);
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
        throw new ReplicationException.UnavailableException("Interrupted while connecting metadata store", ie);
    } catch (TextFormat.ParseException pe) {
        throw new ReplicationException.UnavailableException("Error parsing proto message", pe);
    }
}
Also used : GetResult(org.apache.pulsar.metadata.api.GetResult) TextFormat(com.google.protobuf.TextFormat) ReplicationException(org.apache.bookkeeper.replication.ReplicationException) ExecutionException(java.util.concurrent.ExecutionException) UnderreplicatedLedgerFormat(org.apache.bookkeeper.proto.DataFormats.UnderreplicatedLedgerFormat)

Aggregations

GetResult (org.apache.pulsar.metadata.api.GetResult)62 ExecutionException (java.util.concurrent.ExecutionException)24 Test (org.testng.annotations.Test)24 Optional (java.util.Optional)18 MetadataStore (org.apache.pulsar.metadata.api.MetadataStore)18 CompletableFuture (java.util.concurrent.CompletableFuture)17 ReplicationException (org.apache.bookkeeper.replication.ReplicationException)15 Cleanup (lombok.Cleanup)13 EnumSet (java.util.EnumSet)12 MetadataStoreException (org.apache.pulsar.metadata.api.MetadataStoreException)12 Stat (org.apache.pulsar.metadata.api.Stat)12 CreateOption (org.apache.pulsar.metadata.api.extended.CreateOption)12 List (java.util.List)11 TimeUnit (java.util.concurrent.TimeUnit)11 InvalidProtocolBufferException (com.google.protobuf.InvalidProtocolBufferException)9 Set (java.util.Set)9 CompletionException (java.util.concurrent.CompletionException)9 BeforeMethod (org.testng.annotations.BeforeMethod)9 Lists (com.google.common.collect.Lists)8 ArrayList (java.util.ArrayList)8