Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -44,28 +44,32 @@ public class OmidTransactionContext implements PhoenixTransactionContext {

private static final Logger LOGGER = LoggerFactory.getLogger(OmidTransactionContext.class);

private HBaseTransactionManager tm;
// The context does not keep the transaction manager. It gets the current manager from the
// provider on each call. Tests can replace that manager and close the old one, so a kept
// reference can become stale. In production the manager does not change.
private OmidTransactionProvider.OmidTransactionClient client;
private HBaseTransaction tx;

public OmidTransactionContext() {
this.tx = null;
this.tm = null;
this.client = null;
}

public OmidTransactionContext(PhoenixConnection connection) throws SQLException {
PhoenixTransactionClient client =
connection.getQueryServices().initTransactionClient(getProvider());
assert (client instanceof OmidTransactionProvider.OmidTransactionClient);
this.tm = ((OmidTransactionProvider.OmidTransactionClient) client).getTransactionClient();
PhoenixTransactionClient c = connection.getQueryServices().initTransactionClient(getProvider());
assert c instanceof OmidTransactionProvider.OmidTransactionClient;
this.client = (OmidTransactionProvider.OmidTransactionClient) c;
this.tx = null;
}

public OmidTransactionContext(byte[] txnBytes) throws InvalidProtocolBufferException {
this();
if (txnBytes != null && txnBytes.length > 0) {
TSOProto.Transaction transaction = TSOProto.Transaction.parseFrom(txnBytes);
HBaseTransactionManager m = tm();
tx = new HBaseTransaction(transaction.getTimestamp(), transaction.getEpoch(),
new HashSet<HBaseCellId>(), new HashSet<HBaseCellId>(), null, tm.isLowLatency());
new HashSet<HBaseCellId>(), new HashSet<HBaseCellId>(), null,
m != null && m.isLowLatency());
} else {
tx = null;
}
Expand All @@ -75,33 +79,39 @@ public OmidTransactionContext(PhoenixTransactionContext ctx, boolean subTask) {
assert (ctx instanceof OmidTransactionContext);
OmidTransactionContext omidTransactionContext = (OmidTransactionContext) ctx;

this.tm = omidTransactionContext.tm;
this.client = omidTransactionContext.client;

if (subTask) {
if (omidTransactionContext.isTransactionRunning()) {
Transaction transaction = omidTransactionContext.getTransaction();
HBaseTransactionManager m = tm();
this.tx = new HBaseTransaction(transaction.getTransactionId(), transaction.getEpoch(),
new HashSet<HBaseCellId>(), new HashSet<HBaseCellId>(), this.tm,
transaction.getReadTimestamp(), transaction.getWriteTimestamp(), tm.isLowLatency());
new HashSet<HBaseCellId>(), new HashSet<HBaseCellId>(), m, transaction.getReadTimestamp(),
transaction.getWriteTimestamp(), m != null && m.isLowLatency());
} else {
this.tx = null;
}

this.tm = null;
this.client = null;
} else {
this.tx = omidTransactionContext.getTransaction();
}
}

private HBaseTransactionManager tm() {
return client == null ? null : client.getTransactionClient();
Comment thread
apurtell marked this conversation as resolved.
Resolved
}

@Override
public void begin() throws SQLException {
if (tm == null) {
HBaseTransactionManager m = tm();
if (m == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.NULL_TRANSACTION_CONTEXT).build()
.buildException();
}

try {
tx = (HBaseTransaction) tm.begin();
tx = (HBaseTransaction) m.begin();
} catch (TransactionException e) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.TRANSACTION_FAILED)
.setMessage(e.getMessage()).setRootCause(e).build().buildException();
Expand All @@ -110,10 +120,13 @@ public void begin() throws SQLException {

@Override
public void commit() throws SQLException {
if (tx == null || tm == null) return;
HBaseTransactionManager m = tm();
if (tx == null || m == null) {
return;
}

try {
tm.commit(tx);
m.commit(tx);
} catch (TransactionException e) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.TRANSACTION_FAILED)
.setMessage(e.getMessage()).setRootCause(e).build().buildException();
Expand All @@ -125,12 +138,13 @@ public void commit() throws SQLException {

@Override
public void abort() throws SQLException {
if (tx == null || tm == null || tx.getStatus() != Status.RUNNING) {
HBaseTransactionManager m = tm();
if (tx == null || m == null || tx.getStatus() != Status.RUNNING) {
return;
}

try {
tm.rollback(tx);
m.rollback(tx);
} catch (TransactionException e) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.TRANSACTION_FAILED)
.setMessage(e.getMessage()).setRootCause(e).build().buildException();
Expand All @@ -149,9 +163,14 @@ public void checkpoint(boolean hasUncommittedData) throws SQLException {

@Override
public void commitDDLFence(PTable dataTable) throws SQLException {
HBaseTransactionManager m = tm();
if (m == null) {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.NULL_TRANSACTION_CONTEXT).build()
.buildException();
}

try {
tx = (HBaseTransaction) tm.fence(dataTable.getName().getBytes());
tx = (HBaseTransaction) m.fence(dataTable.getName().getBytes());
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Added write fence at ~" + tx.getReadTimestamp());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
public class OmidTransactionProvider implements PhoenixTransactionProvider {
private static final OmidTransactionProvider INSTANCE = new OmidTransactionProvider();

private HBaseTransactionManager transactionManager = null;
// Tests can replace the manager while other threads read it. The volatile field makes the
// new manager visible to those threads without a lock.
private volatile HBaseTransactionManager transactionManager = null;
private volatile CommitTable.Client commitTableClient = null;

public static final OmidTransactionProvider getInstance() {
Expand Down Expand Up @@ -78,18 +80,22 @@ public PhoenixTransactionClient getTransactionClient(Configuration config,
}
}

return new OmidTransactionClient(transactionManager);
return new OmidTransactionClient(this);
}

/**
* Gives the current {@link HBaseTransactionManager} of the provider. The client does not keep its
* own reference to the manager.
*/
static class OmidTransactionClient implements PhoenixTransactionClient {
private final HBaseTransactionManager transactionManager;
private final OmidTransactionProvider provider;

public OmidTransactionClient(HBaseTransactionManager transactionManager) {
this.transactionManager = transactionManager;
OmidTransactionClient(OmidTransactionProvider provider) {
this.provider = provider;
}

public HBaseTransactionManager getTransactionClient() {
return transactionManager;
return provider.transactionManager;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,18 @@ public class ConnectionQueryServicesTestImpl extends ConnectionQueryServicesImpl
private Set<PhoenixConnection> connections =
Collections.newSetFromMap(new ConcurrentHashMap<PhoenixConnection, Boolean>());
// Use Provider.values() instead of Provider.available() here because array accesses will be
// indexed by ordinal.
// indexed by ordinal. Each slot holds the shared service that this instance uses, if any.
private final PhoenixTransactionService[] txServices =
new PhoenixTransactionService[TransactionFactory.Provider.values().length];
// All connection services in the JVM share one test transaction service for each provider.
// The provider is a singleton, and each region keeps the commit table client that is current
// when the region opens. A second service replaces that client, and readers can then miss
// commits. Each shared service counts the connection services that use it. The last one to
// release the service closes it.
private static final PhoenixTransactionService[] SHARED_TX_SERVICES =
new PhoenixTransactionService[TransactionFactory.Provider.values().length];
private static final int[] SHARED_TX_SERVICE_USERS =
new int[TransactionFactory.Provider.values().length];

public ConnectionQueryServicesTestImpl(QueryServices services, ConnectionInfo info,
Properties props) throws SQLException {
Expand Down Expand Up @@ -90,13 +99,22 @@ public void close() throws SQLException {
connections = new ArrayList<>(this.connections);
this.connections = Sets.newHashSet();

// shut down the tx client service if we created one to support transactions
for (PhoenixTransactionService service : txServices) {
// Release the shared transaction services that this instance uses. The last user shuts
// a service down and clears its slot, so that the next connection service starts a new
// service.
for (int i = 0; i < txServices.length; i++) {
PhoenixTransactionService service = txServices[i];
if (service != null) {
try {
service.close();
} catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
txServices[i] = null;
synchronized (SHARED_TX_SERVICES) {
if (SHARED_TX_SERVICES[i] == service && --SHARED_TX_SERVICE_USERS[i] == 0) {
SHARED_TX_SERVICES[i] = null;
try {
service.close();
} catch (IOException e) {
LOGGER.warn(e.getMessage(), e);
}
}
}
}
}
Expand All @@ -113,11 +131,18 @@ public void close() throws SQLException {
@Override
public synchronized PhoenixTransactionClient initTransactionClient(Provider provider)
throws SQLException {
PhoenixTransactionService txService = txServices[provider.ordinal()];
if (txService == null) {
int port = TestUtil.getRandomPort();
txService = txServices[provider.ordinal()] =
TransactionServiceManager.startTransactionService(provider, config, connectionInfo, port);
int i = provider.ordinal();
if (txServices[i] == null) {
// Start a service only when no other connection service uses a live one.
synchronized (SHARED_TX_SERVICES) {
if (SHARED_TX_SERVICES[i] == null) {
int port = TestUtil.getRandomPort();
SHARED_TX_SERVICES[i] = TransactionServiceManager.startTransactionService(provider,
config, connectionInfo, port);
}
txServices[i] = SHARED_TX_SERVICES[i];
SHARED_TX_SERVICE_USERS[i]++;
}
}
return super.initTransactionClient(provider);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* 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.phoenix.transaction;

import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.withSettings;

import org.apache.omid.committable.CommitTable;
import org.apache.omid.transaction.HBaseTransaction;
import org.apache.omid.transaction.HBaseTransactionManager;
import org.apache.omid.transaction.Transaction.Status;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.query.ConnectionQueryServices;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.MockMakers;

/**
* Tests that a kept Omid client and context use the current transaction manager of the provider.
* They must not use the manager that is current when they are created.
*/
public class OmidTransactionContextTest {

private final OmidTransactionProvider provider = OmidTransactionProvider.getInstance();
private HBaseTransactionManager savedManager;
private CommitTable.Client savedCommitTableClient;

@Before
public void setUp() {
// The provider is a singleton. Keep its state so that the test can restore it.
savedManager =
new OmidTransactionProvider.OmidTransactionClient(provider).getTransactionClient();
savedCommitTableClient = provider.getCommitTableClient();
}

@After
public void tearDown() {
provider.injectTestService(savedManager, savedCommitTableClient);
}

@Test
public void testRetainedClientAndContextUseReplacementManager() throws Exception {
// The context calls final methods of the manager. Only the inline mock maker can stub them.
HBaseTransactionManager managerA =
mock(HBaseTransactionManager.class, withSettings().mockMaker(MockMakers.INLINE));
HBaseTransactionManager managerB =
mock(HBaseTransactionManager.class, withSettings().mockMaker(MockMakers.INLINE));
CommitTable.Client commitTableA = mock(CommitTable.Client.class);
CommitTable.Client commitTableB = mock(CommitTable.Client.class);

// Make the client and the context while manager A is current.
provider.injectTestService(managerA, commitTableA);
OmidTransactionProvider.OmidTransactionClient client =
(OmidTransactionProvider.OmidTransactionClient) provider.getTransactionClient(null, null);
ConnectionQueryServices services = mock(ConnectionQueryServices.class);
when(services.initTransactionClient(TransactionFactory.Provider.OMID)).thenReturn(client);
PhoenixConnection connection = mock(PhoenixConnection.class);
when(connection.getQueryServices()).thenReturn(services);
OmidTransactionContext context = new OmidTransactionContext(connection);

// Replace the manager before the next transaction starts.
provider.injectTestService(managerB, commitTableB);
HBaseTransaction tx1 = mock(HBaseTransaction.class);
HBaseTransaction tx2 = mock(HBaseTransaction.class);
when(tx2.getStatus()).thenReturn(Status.RUNNING);
when(managerB.begin()).thenReturn(tx1, tx2);

assertSame(managerB, client.getTransactionClient());

context.begin();
context.commit();
context.begin();
context.abort();

verify(managerB, times(2)).begin();
verify(managerB).commit(tx1);
verify(managerB).rollback(tx2);
verifyNoInteractions(managerA);
}
}
Loading