|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | +package org.apache.kafka.trogdor.workload; |
| 18 | + |
| 19 | +import com.fasterxml.jackson.annotation.JsonCreator; |
| 20 | +import com.fasterxml.jackson.annotation.JsonProperty; |
| 21 | +import org.apache.kafka.common.utils.Time; |
| 22 | + |
| 23 | +/** |
| 24 | + * A transactions generator where we commit a transaction every N milliseconds |
| 25 | + */ |
| 26 | +public class TimeIntervalTransactionsGenerator implements TransactionGenerator { |
| 27 | + |
| 28 | + private static final long NULL_START_MS = -1; |
| 29 | + |
| 30 | + private final Time time; |
| 31 | + private final int intervalMs; |
| 32 | + |
| 33 | + private long lastTransactionStartMs = NULL_START_MS; |
| 34 | + |
| 35 | + @JsonCreator |
| 36 | + public TimeIntervalTransactionsGenerator(@JsonProperty("transactionIntervalMs") int intervalMs) { |
| 37 | + this(intervalMs, Time.SYSTEM); |
| 38 | + } |
| 39 | + |
| 40 | + TimeIntervalTransactionsGenerator(@JsonProperty("transactionIntervalMs") int intervalMs, |
| 41 | + Time time) { |
| 42 | + if (intervalMs < 1) { |
| 43 | + throw new IllegalArgumentException("Cannot have a negative interval"); |
| 44 | + } |
| 45 | + this.time = time; |
| 46 | + this.intervalMs = intervalMs; |
| 47 | + } |
| 48 | + |
| 49 | + @JsonProperty |
| 50 | + public int transactionIntervalMs() { |
| 51 | + return intervalMs; |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public synchronized TransactionAction nextAction() { |
| 56 | + if (lastTransactionStartMs == NULL_START_MS) { |
| 57 | + lastTransactionStartMs = time.milliseconds(); |
| 58 | + return TransactionAction.BEGIN_TRANSACTION; |
| 59 | + } |
| 60 | + if (time.milliseconds() - lastTransactionStartMs >= intervalMs) { |
| 61 | + lastTransactionStartMs = NULL_START_MS; |
| 62 | + return TransactionAction.COMMIT_TRANSACTION; |
| 63 | + } |
| 64 | + |
| 65 | + return TransactionAction.NO_OP; |
| 66 | + } |
| 67 | +} |
0 commit comments