Search in sources :

Example 11 with EventTypePartition

use of org.zalando.nakadi.domain.EventTypePartition in project nakadi by zalando.

the class StreamingState method reconfigureKafkaConsumer.

private void reconfigureKafkaConsumer(final boolean forceSeek) {
    if (eventConsumer == null) {
        throw new IllegalStateException("kafkaConsumer should not be null when calling reconfigureKafkaConsumer method");
    }
    final Set<EventTypePartition> newAssignment = offsets.keySet().stream().filter(o -> !this.releasingPartitions.containsKey(o)).collect(Collectors.toSet());
    if (forceSeek) {
        // removing all the current assignments for real consumer.
        try {
            eventConsumer.reassign(Collections.emptyList());
        } catch (final NakadiException | InvalidCursorException ex) {
            throw new NakadiRuntimeException(ex);
        }
    }
    final Set<EventTypePartition> currentAssignment = eventConsumer.getAssignment();
    getLog().info("Changing kafka assignment from {} to {}", Arrays.deepToString(currentAssignment.toArray()), Arrays.deepToString(newAssignment.toArray()));
    if (!currentAssignment.equals(newAssignment)) {
        try {
            final Map<EventTypePartition, NakadiCursor> beforeFirst = getBeforeFirstCursors(newAssignment);
            final List<NakadiCursor> cursors = newAssignment.stream().map(pk -> {
                final NakadiCursor beforeFirstAvailable = beforeFirst.get(pk);
                // Checks that current cursor is still available in storage
                offsets.get(pk).ensureDataAvailable(beforeFirstAvailable);
                return offsets.get(pk).getSentOffset();
            }).collect(Collectors.toList());
            eventConsumer.reassign(cursors);
        } catch (NakadiException | InvalidCursorException ex) {
            throw new NakadiRuntimeException(ex);
        }
    }
}
Also used : ConsumedEvent(org.zalando.nakadi.domain.ConsumedEvent) Arrays(java.util.Arrays) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) IdleStreamWatcher(org.zalando.nakadi.service.subscription.IdleStreamWatcher) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) LoggerFactory(org.slf4j.LoggerFactory) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) HashMap(java.util.HashMap) NakadiException(org.zalando.nakadi.exceptions.NakadiException) ZkSubscriptionClient(org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClient) Partition(org.zalando.nakadi.service.subscription.model.Partition) HashSet(java.util.HashSet) Meter(com.codahale.metrics.Meter) OptionalLong(java.util.OptionalLong) JSONObject(org.json.JSONObject) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Map(java.util.Map) NakadiKpiPublisher(org.zalando.nakadi.service.NakadiKpiPublisher) ZkSubscription(org.zalando.nakadi.service.subscription.zk.ZkSubscription) PartitionStatistics(org.zalando.nakadi.domain.PartitionStatistics) StreamKpiData(org.zalando.nakadi.metrics.StreamKpiData) Set(java.util.Set) IOException(java.io.IOException) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) EventConsumer(org.zalando.nakadi.repository.EventConsumer) List(java.util.List) Stream(java.util.stream.Stream) Timeline(org.zalando.nakadi.domain.Timeline) Closeable(java.io.Closeable) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) SubscriptionCursor(org.zalando.nakadi.view.SubscriptionCursor) MetricUtils(org.zalando.nakadi.metrics.MetricUtils) Comparator(java.util.Comparator) Collections(java.util.Collections) Client(org.zalando.nakadi.security.Client) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) NakadiCursor(org.zalando.nakadi.domain.NakadiCursor) InvalidCursorException(org.zalando.nakadi.exceptions.InvalidCursorException) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) NakadiException(org.zalando.nakadi.exceptions.NakadiException)

Example 12 with EventTypePartition

use of org.zalando.nakadi.domain.EventTypePartition in project nakadi by zalando.

the class AbstractZkSubscriptionClient method commitOffsets.

@Override
public List<Boolean> commitOffsets(final List<SubscriptionCursorWithoutToken> cursors, final Comparator<SubscriptionCursorWithoutToken> comparator) {
    final Map<EventTypePartition, List<SubscriptionCursorWithoutToken>> grouped = cursors.stream().collect(Collectors.groupingBy(SubscriptionCursorWithoutToken::getEventTypePartition));
    try {
        final Map<EventTypePartition, Iterator<Boolean>> committedOverall = new HashMap<>();
        for (final Map.Entry<EventTypePartition, List<SubscriptionCursorWithoutToken>> entry : grouped.entrySet()) {
            final String offsetPath = getOffsetPath(entry.getKey());
            final List<Boolean> committed;
            committed = executeWithRetry(() -> {
                final Stat stat = new Stat();
                final byte[] currentOffsetData = getCurator().getData().storingStatIn(stat).forPath(offsetPath);
                final String currentMaxOffset = new String(currentOffsetData, UTF_8);
                SubscriptionCursorWithoutToken currentMaxCursor = new SubscriptionCursorWithoutToken(entry.getKey().getEventType(), entry.getKey().getPartition(), currentMaxOffset);
                final List<Boolean> commits = Lists.newArrayList();
                for (final SubscriptionCursorWithoutToken cursor : entry.getValue()) {
                    if (comparator.compare(cursor, currentMaxCursor) > 0) {
                        currentMaxCursor = cursor;
                        commits.add(true);
                    } else {
                        commits.add(false);
                    }
                }
                if (!currentMaxCursor.getOffset().equals(currentMaxOffset)) {
                    getLog().info("Committing {} to {}", currentMaxCursor.getOffset(), offsetPath);
                    getCurator().setData().withVersion(stat.getVersion()).forPath(offsetPath, currentMaxCursor.getOffset().getBytes(Charsets.UTF_8));
                }
                return commits;
            }, new RetryForSpecifiedCountStrategy<List<Boolean>>(COMMIT_CONFLICT_RETRY_TIMES).withExceptionsThatForceRetry(KeeperException.BadVersionException.class));
            committedOverall.put(entry.getKey(), Optional.ofNullable(committed).orElse(Collections.nCopies(entry.getValue().size(), false)).iterator());
        }
        return cursors.stream().map(cursor -> committedOverall.get(cursor.getEventTypePartition()).next()).collect(Collectors.toList());
    } catch (final Exception ex) {
        throw new NakadiRuntimeException(ex);
    }
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) RequestInProgressException(org.zalando.nakadi.exceptions.runtime.RequestInProgressException) Arrays(java.util.Arrays) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Session(org.zalando.nakadi.service.subscription.model.Session) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) NodeCache(org.apache.curator.framework.recipes.cache.NodeCache) InterProcessSemaphoreMutex(org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex) Stat(org.apache.zookeeper.data.Stat) MyNakadiRuntimeException1(org.zalando.nakadi.exceptions.runtime.MyNakadiRuntimeException1) UTF_8(com.google.common.base.Charsets.UTF_8) Function(java.util.function.Function) Retryer.executeWithRetry(org.echocat.jomon.runtime.concurrent.Retryer.executeWithRetry) RetryForSpecifiedCountStrategy(org.echocat.jomon.runtime.concurrent.RetryForSpecifiedCountStrategy) UnableProcessException(org.zalando.nakadi.exceptions.UnableProcessException) Lists(com.google.common.collect.Lists) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Map(java.util.Map) OperationInterruptedException(org.zalando.nakadi.exceptions.runtime.OperationInterruptedException) Charsets(com.google.common.base.Charsets) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Iterator(java.util.Iterator) Collection(java.util.Collection) IOException(java.io.IOException) OperationTimeoutException(org.zalando.nakadi.exceptions.runtime.OperationTimeoutException) ZookeeperException(org.zalando.nakadi.exceptions.runtime.ZookeeperException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) Closeable(java.io.Closeable) Optional(java.util.Optional) Comparator(java.util.Comparator) Collections(java.util.Collections) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) HashMap(java.util.HashMap) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) RequestInProgressException(org.zalando.nakadi.exceptions.runtime.RequestInProgressException) UnableProcessException(org.zalando.nakadi.exceptions.UnableProcessException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) OperationInterruptedException(org.zalando.nakadi.exceptions.runtime.OperationInterruptedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) OperationTimeoutException(org.zalando.nakadi.exceptions.runtime.OperationTimeoutException) ZookeeperException(org.zalando.nakadi.exceptions.runtime.ZookeeperException) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) Stat(org.apache.zookeeper.data.Stat) Iterator(java.util.Iterator) List(java.util.List) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Map(java.util.Map) KeeperException(org.apache.zookeeper.KeeperException)

Example 13 with EventTypePartition

use of org.zalando.nakadi.domain.EventTypePartition in project nakadi by zalando.

the class NewZkSubscriptionClient method transfer.

@Override
public void transfer(final String sessionId, final Collection<EventTypePartition> partitions) throws NakadiRuntimeException, SubscriptionNotInitializedException {
    getLog().info("session " + sessionId + " releases partitions " + partitions);
    final Topology topology = getTopology();
    final List<Partition> changeSet = new ArrayList<>();
    for (final EventTypePartition etp : partitions) {
        final Partition candidate = Stream.of(topology.getPartitions()).filter(p -> p.getKey().equals(etp)).findAny().get();
        if (sessionId.equals(candidate.getSession()) && candidate.getState() == Partition.State.REASSIGNING) {
            changeSet.add(candidate.toState(Partition.State.ASSIGNED, candidate.getNextSession(), null));
        }
    }
    if (!changeSet.isEmpty()) {
        // The list of sessions didn't change, therefore one should not update sessionsHash.
        updatePartitionsConfiguration(topology.getSessionsHash(), changeSet.toArray(new Partition[changeSet.size()]));
    }
}
Also used : EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Partition(org.zalando.nakadi.service.subscription.model.Partition) ArrayList(java.util.ArrayList) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition)

Example 14 with EventTypePartition

use of org.zalando.nakadi.domain.EventTypePartition in project nakadi by zalando.

the class CursorsService method getSubscriptionCursors.

public List<SubscriptionCursorWithoutToken> getSubscriptionCursors(final String subscriptionId) throws NakadiException, ServiceTemporarilyUnavailableException {
    final Subscription subscription = subscriptionRepository.getSubscription(subscriptionId);
    final ZkSubscriptionClient zkSubscriptionClient = zkSubscriptionFactory.createClient(subscription, "subscription." + subscriptionId + ".get_cursors");
    final ImmutableList.Builder<SubscriptionCursorWithoutToken> cursorsListBuilder = ImmutableList.builder();
    Partition[] partitions;
    try {
        partitions = zkSubscriptionClient.getTopology().getPartitions();
    } catch (final SubscriptionNotInitializedException ex) {
        partitions = new Partition[] {};
    }
    final Map<EventTypePartition, SubscriptionCursorWithoutToken> positions = zkSubscriptionClient.getOffsets(Stream.of(partitions).map(Partition::getKey).collect(Collectors.toList()));
    for (final Partition p : partitions) {
        cursorsListBuilder.add(positions.get(p.getKey()));
    }
    return cursorsListBuilder.build();
}
Also used : SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Partition(org.zalando.nakadi.service.subscription.model.Partition) ZkSubscriptionClient(org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClient) ImmutableList(com.google.common.collect.ImmutableList) SubscriptionNotInitializedException(org.zalando.nakadi.service.subscription.zk.SubscriptionNotInitializedException) Subscription(org.zalando.nakadi.domain.Subscription) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition)

Example 15 with EventTypePartition

use of org.zalando.nakadi.domain.EventTypePartition in project nakadi by zalando.

the class SubscriptionRebalancer method apply.

@Override
public Partition[] apply(final Collection<Session> sessions, final Partition[] currentPartitions) {
    final List<String> activeSessions = sessions.stream().map(Session::getId).collect(Collectors.toList());
    final List<Partition> partitionsLeft = Lists.newArrayList(currentPartitions);
    final List<Partition> changedPartitions = new ArrayList<>();
    final List<Session> sessionsWithSpecifiedPartitions = sessions.stream().filter(s -> !s.getRequestedPartitions().isEmpty()).collect(Collectors.toList());
    // go through all sessions that directly requested partitions to stream
    for (final Session session : sessionsWithSpecifiedPartitions) {
        for (final EventTypePartition requestedPartition : session.getRequestedPartitions()) {
            // find a partition that is requested and assign it to a session that requests it
            final Partition partition = partitionsLeft.stream().filter(p -> p.getKey().equals(requestedPartition)).findFirst().orElseThrow(() -> new RebalanceConflictException("Two existing sessions request the same partition: " + requestedPartition));
            partitionsLeft.remove(partition);
            // if this partition is not assigned to this session - move it
            if (!session.getId().equals(partition.getSession())) {
                final Partition movedPartition = partition.moveToSessionId(session.getId(), activeSessions);
                changedPartitions.add(movedPartition);
            }
        }
    }
    // for the rest of partitions/sessions perform a rebalance based on partitions count
    final List<Session> autoBalanceSessions = sessions.stream().filter(s -> s.getRequestedPartitions().isEmpty()).collect(Collectors.toList());
    if (!autoBalanceSessions.isEmpty() && !partitionsLeft.isEmpty()) {
        final Partition[] partitionsChangedByAutoRebalance = rebalanceByWeight(autoBalanceSessions, partitionsLeft.toArray(new Partition[partitionsLeft.size()]));
        changedPartitions.addAll(Arrays.asList(partitionsChangedByAutoRebalance));
    }
    return changedPartitions.toArray(new Partition[changedPartitions.size()]);
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Session(org.zalando.nakadi.service.subscription.model.Session) Collection(java.util.Collection) BiFunction(java.util.function.BiFunction) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Partition(org.zalando.nakadi.service.subscription.model.Partition) RebalanceConflictException(org.zalando.nakadi.exceptions.runtime.RebalanceConflictException) List(java.util.List) Lists(com.google.common.collect.Lists) Stream(java.util.stream.Stream) Map(java.util.Map) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Partition(org.zalando.nakadi.service.subscription.model.Partition) RebalanceConflictException(org.zalando.nakadi.exceptions.runtime.RebalanceConflictException) ArrayList(java.util.ArrayList) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Session(org.zalando.nakadi.service.subscription.model.Session)

Aggregations

EventTypePartition (org.zalando.nakadi.domain.EventTypePartition)27 Test (org.junit.Test)16 Partition (org.zalando.nakadi.service.subscription.model.Partition)15 Session (org.zalando.nakadi.service.subscription.model.Session)11 SubscriptionCursorWithoutToken (org.zalando.nakadi.view.SubscriptionCursorWithoutToken)9 NakadiCursor (org.zalando.nakadi.domain.NakadiCursor)6 Map (java.util.Map)5 NakadiRuntimeException (org.zalando.nakadi.exceptions.NakadiRuntimeException)5 HashMap (java.util.HashMap)4 List (java.util.List)4 Stream (java.util.stream.Stream)4 InvalidCursorException (org.zalando.nakadi.exceptions.InvalidCursorException)4 Arrays (java.util.Arrays)3 Collection (java.util.Collection)3 Collections (java.util.Collections)3 TimeUnit (java.util.concurrent.TimeUnit)3 Collectors (java.util.stream.Collectors)3 Subscription (org.zalando.nakadi.domain.Subscription)3 NakadiException (org.zalando.nakadi.exceptions.NakadiException)3 ZkSubscriptionClient (org.zalando.nakadi.service.subscription.zk.ZkSubscriptionClient)3