murong00 commented on a change in pull request #4210: #4209: Pulsar IO Source Connector for Couchbase URL: https://github.com/apache/pulsar/pull/4210#discussion_r282772388
########## File path: pulsar-io/couchbase/src/main/java/org/apache/pulsar/io/cb/CBAbstractSource.java ########## @@ -0,0 +1,314 @@ +/** + * 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.pulsar.io.cb; + +import com.couchbase.client.core.event.CouchbaseEvent; +import com.couchbase.client.dcp.*; +import com.couchbase.client.dcp.config.CompressionMode; +import com.couchbase.client.dcp.message.*; +import com.couchbase.client.dcp.transport.netty.ChannelFlowController; +import com.couchbase.client.deps.io.netty.buffer.ByteBuf; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.slf4j.Slf4j; +import org.apache.pulsar.functions.api.Record; +import org.apache.pulsar.io.core.PushSource; +import org.apache.pulsar.io.core.SourceContext; +import rx.CompletableSubscriber; +import rx.Subscription; + +import java.io.Closeable; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import static com.couchbase.client.dcp.config.DcpControl.Names.ENABLE_NOOP; +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +@Slf4j +public abstract class CBAbstractSource<T> extends PushSource<T> { + protected Thread thread = null; + + private CBSourceConfig cbSourceConfig; + + private Client client; + + protected final Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread thread, Throwable ex) { + log.error("{} has an error", thread.getName(), ex); + } + }; + + private ConcurrentMap<Short, DcpSnapshotMarkerRequestMeta> snapshots = new ConcurrentHashMap(); + + /** + * Open connector with configuration + * + * @param config initialization config + * @param sourceContext + * @throws Exception IO type exceptions when opening a connector + */ + @Override + public void open(Map<String, Object> config, SourceContext sourceContext) throws Exception { + log.info("opening connection to couchbase."); + + cbSourceConfig = CBSourceConfig.load(config); +// cbSourceConfig.validate(); + + client = Client.configure() + .connectionNameGenerator(DefaultConnectionNameGenerator.forProduct( + "pulsar-couchbase-connector", "version1", + cbSourceConfig.getConnectionName())) + .connectTimeout(cbSourceConfig.getConnectionTimeOut()) + .hostnames(cbSourceConfig.getHostnames()) + .bucket(cbSourceConfig.getBucket()) + .username(cbSourceConfig.getUsername()) + .password(cbSourceConfig.getPassword()) + .controlParam(ENABLE_NOOP, "true") + .compression(getCompressedMode()) + .mitigateRollbacks(cbSourceConfig.getPersistencePollingInterval(), MILLISECONDS) + .flowControl(cbSourceConfig.getFlowControlBufferSizeInBytes()) + .bufferAckWatermark(60) + .sslEnabled(cbSourceConfig.getSslEnabled()) + .sslKeystoreFile(cbSourceConfig.getSslKeystoreFile()) + .sslKeystorePassword(cbSourceConfig.getSslKeystorePassword()) + .build(); + + log.info("opened connection to couchbase successfully."); + } + + protected void process() { + client.dataEventHandler(new DataEventHandler() { + @Override + public void onEvent(ChannelFlowController flowController, ByteBuf event) { + byte[] message = null; + long id = -1L; + + if (cbSourceConfig.getUseSnapshots()) { + if (DcpMutationMessage.is(event)) { + message = DcpMutationMessage.contentBytes(event); + id = DcpMutationMessage.bySeqno(event); + } + else if (DcpDeletionMessage.is(event)) { + message = MessageUtil.getContentAsByteArray(event); + id = DcpDeletionMessage.bySeqno(event); + } + } + else { + message = new byte[event.readableBytes()]; + event.readBytes(message); + } + + try { + CBRecord cbRecord = new CBRecord(); + cbRecord.setRecord(extractValue(message)); + cbRecord.setId(id); + consume(cbRecord); + + flowController.ack(event); + event.release(); + } + catch (Exception ex) { + log.error("process error!", ex); + + event.retain(); + } + } + }); + + client.controlEventHandler(new ControlEventHandler() { + @Override + public void onEvent(ChannelFlowController flowController, ByteBuf event) { + try { + log.info("Control Event: {}", event.toString()); + + if (DcpSnapshotMarkerRequest.is(event) && cbSourceConfig.getUseSnapshots()) { + DcpSnapshotMarkerRequestMeta snapshot = new DcpSnapshotMarkerRequestMeta(event); + + DcpSnapshotMarkerRequestMeta existingSnapshot = snapshots.put(snapshot.getPartition(), snapshot); + + if (existingSnapshot != null) { + log.warn("Incomplete snapshot detected: {}", existingSnapshot); + } + } + + if (RollbackMessage.is(event)) { + final short vbucket = RollbackMessage.vbucket(event); + final long seqNo = RollbackMessage.seqno(event); + + log.warn("Rolling back partition {} to seqno {}", vbucket, seqNo); + + // Netty IO thread + client.rollbackAndRestartStream(vbucket, seqNo) + .subscribe(new CompletableSubscriber() { + private Subscription subscription; + + @Override + public void onCompleted() { + log.info("Rollback for vbucket {} complete", vbucket); + + // TODO: find if exclusive unsubscribe needed ? + if (!subscription.isUnsubscribed()) { + subscription.unsubscribe(); + } + } + + @Override + public void onError(Throwable throwable) { + log.error("Failed to rollback vbucket {} to seqNo {}", vbucket, seqNo, throwable); + } + + @Override + public void onSubscribe(Subscription subscription) { + log.info(subscription.toString()); + + this.subscription = subscription; + } + }); + } + } + catch (Throwable throwable) { + log.error("Exception in ControlEventHandler", throwable); + } + finally { + //TODO: push to queue + event.release(); + } + } + }); + + client.systemEventHandler(new SystemEventHandler() { + @Override + public void onEvent(CouchbaseEvent event) { + log.info("System Event: {}", event.type().toString()); + } + }); + } + + protected void start() { + Objects.requireNonNull(client, "client is null"); + + + thread = new Thread(new Runnable() { + @Override + public void run() { + process(); + + client.connect().await(); + + //FIXME + client.initializeState(StreamFrom.BEGINNING, StreamTo.NOW).await(); Review comment: seems `initializeState(StreamFrom.BEGINNING, StreamTo.INFINITY)).await()`? ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services
