index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/SpinalTap/spinaltap-model/src/test/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/test/java/com/airbnb/spinaltap/mysql/mutation/MysqlUpdateMutationTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import static org.junit.Assert.assertEquals; import com.airbnb.spinaltap.mysql.mutation.schema.Column; import com.airbnb.spinaltap.mysql.mutation.schema.ColumnDataType; import com.airbnb.spinaltap.mysql.mutation.schema.ColumnMetadata; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import com.airbnb.spinaltap.mysql.mutation.schema.Table; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; public class MysqlUpdateMutationTest { @Test public void testAsColumnValues() throws Exception { Table table = new Table( 1, "table_name", "db_name", null, ImmutableList.of(new ColumnMetadata("id", ColumnDataType.LONGLONG, false, 0)), ImmutableList.of()); Row row = new Row(table, ImmutableMap.of("id", new Column(table.getColumns().get("id"), 2))); assertEquals(ImmutableMap.of("id", 2), MysqlUpdateMutation.asColumnValues(row)); } }
2,000
0
Create_ds/SpinalTap/spinaltap-model/src/test/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/test/java/com/airbnb/spinaltap/mysql/schema/RowTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.schema; import static org.junit.Assert.*; import com.airbnb.spinaltap.mysql.mutation.schema.Column; import com.airbnb.spinaltap.mysql.mutation.schema.ColumnDataType; import com.airbnb.spinaltap.mysql.mutation.schema.ColumnMetadata; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import com.airbnb.spinaltap.mysql.mutation.schema.Table; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.junit.Test; public class RowTest { private static final int TABLE_ID = 1; private static final String TABLE_NAME = "Users"; private static final String DB_NAME = "test_db"; private static final String ID_COLUMN = "id"; private static final String NAME_COLUMN = "name"; @Test public void testNoPrimaryKey() throws Exception { Table table = new Table( TABLE_ID, TABLE_NAME, DB_NAME, null, ImmutableList.of(new ColumnMetadata(ID_COLUMN, ColumnDataType.LONGLONG, false, 0)), ImmutableList.of()); Row row = new Row( table, ImmutableMap.of(ID_COLUMN, new Column(table.getColumns().get(ID_COLUMN), 1))); assertNull(row.getPrimaryKeyValue()); } @Test public void testNullPrimaryKey() throws Exception { Table table = new Table( TABLE_ID, TABLE_NAME, DB_NAME, null, ImmutableList.of(new ColumnMetadata(ID_COLUMN, ColumnDataType.LONGLONG, true, 0)), ImmutableList.of(ID_COLUMN)); Row row = new Row( table, ImmutableMap.of(ID_COLUMN, new Column(table.getColumns().get(ID_COLUMN), null))); assertEquals("null", row.getPrimaryKeyValue()); } @Test public void testSinglePrimaryKey() throws Exception { Table table = new Table( TABLE_ID, TABLE_NAME, DB_NAME, null, ImmutableList.of( new ColumnMetadata(ID_COLUMN, ColumnDataType.LONGLONG, true, 0), new ColumnMetadata(NAME_COLUMN, ColumnDataType.VARCHAR, false, 1)), ImmutableList.of(ID_COLUMN)); Row row = new Row( table, ImmutableMap.of( ID_COLUMN, new Column(table.getColumns().get(ID_COLUMN), 1), NAME_COLUMN, new Column(table.getColumns().get(NAME_COLUMN), "Bob"))); assertEquals("1", row.getPrimaryKeyValue()); } @Test public void testCompositePrimaryKey() throws Exception { Table table = new Table( TABLE_ID, TABLE_NAME, DB_NAME, null, ImmutableList.of( new ColumnMetadata(ID_COLUMN, ColumnDataType.LONGLONG, true, 0), new ColumnMetadata(NAME_COLUMN, ColumnDataType.VARCHAR, true, 1)), ImmutableList.of(ID_COLUMN, NAME_COLUMN)); Row row = new Row( table, ImmutableMap.of( ID_COLUMN, new Column(table.getColumns().get(ID_COLUMN), 1), NAME_COLUMN, new Column(table.getColumns().get(NAME_COLUMN), "Bob"))); assertEquals("1Bob", row.getPrimaryKeyValue()); } }
2,001
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/Mutation.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.ToString; /** * Base class which represents a data entity change (mutation). * * @param <T> The data entity type (ex: Row, Record, etc...) */ @Getter @ToString @RequiredArgsConstructor public abstract class Mutation<T> { private static final byte INSERT_BYTE = 0x1; private static final byte UPDATE_BYTE = 0x2; private static final byte DELETE_BYTE = 0x3; private static final byte INVALID_BYTE = 0x4; @Getter @RequiredArgsConstructor public enum Type { INSERT(INSERT_BYTE), UPDATE(UPDATE_BYTE), DELETE(DELETE_BYTE), INVALID(INVALID_BYTE); final byte code; public static Type fromCode(byte code) { switch (code) { case INSERT_BYTE: return INSERT; case UPDATE_BYTE: return UPDATE; case DELETE_BYTE: return DELETE; default: return INVALID; } } } private final Metadata metadata; private final Type type; private final T entity; @Getter @ToString @RequiredArgsConstructor public abstract static class Metadata { private final long id; private final long timestamp; } // For use by subclasses that implement a mutation with type UPDATE. protected static Set<String> getUpdatedColumns( final Map<String, ?> previousValues, final Map<String, ?> currentValues) { final Set<String> previousColumns = previousValues.keySet(); final Set<String> currentColumns = currentValues.keySet(); return ImmutableSet.<String>builder() .addAll(Sets.symmetricDifference(currentColumns, previousColumns)) .addAll( Sets.intersection(currentColumns, previousColumns) .stream() .filter( column -> // Use deepEquals to allow testing for equality between two byte arrays. !Objects.deepEquals(previousValues.get(column), currentValues.get(column))) .collect(Collectors.toSet())) .build(); } }
2,002
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/BinlogFilePos.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder; import com.google.common.base.Splitter; import java.io.Serializable; import java.util.Iterator; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** Represents the position in a binlog file. */ @Slf4j @Getter @EqualsAndHashCode @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @JsonDeserialize(builder = BinlogFilePos.Builder.class) public class BinlogFilePos implements Comparable<BinlogFilePos>, Serializable { private static final long serialVersionUID = 1549638989059430876L; private static final Splitter SPLITTER = Splitter.on(':'); private static final String NULL_VALUE = "null"; public static final String DEFAULT_BINLOG_FILE_NAME = "mysql-bin-changelog"; @JsonProperty private String fileName; @JsonProperty private long position; @JsonProperty private long nextPosition; @JsonProperty @Setter private GtidSet gtidSet; @JsonProperty @Setter private String serverUUID; public BinlogFilePos(long fileNumber) { this(fileNumber, 4L, 4L); } public BinlogFilePos(String fileName) { this(fileName, 4L, 4L); } public BinlogFilePos(long fileNumber, long position, long nextPosition) { this(String.format("%s.%06d", DEFAULT_BINLOG_FILE_NAME, fileNumber), position, nextPosition); } public BinlogFilePos( String fileName, long position, long nextPosition, String gtidSet, String serverUUID) { this.fileName = fileName; this.position = position; this.nextPosition = nextPosition; this.serverUUID = serverUUID; if (gtidSet != null) { this.gtidSet = new GtidSet(gtidSet); } } public BinlogFilePos(String fileName, long position, long nextPosition) { this(fileName, position, nextPosition, null, null); } public static BinlogFilePos fromString(@NonNull final String position) { Iterator<String> parts = SPLITTER.split(position).iterator(); String fileName = parts.next(); String pos = parts.next(); String nextPos = parts.next(); if (NULL_VALUE.equals(fileName)) { fileName = null; } return new BinlogFilePos(fileName, Long.parseLong(pos), Long.parseLong(nextPos)); } @JsonIgnore public long getFileNumber() { if (fileName == null) { return Long.MAX_VALUE; } if (fileName.equals("")) { return Long.MIN_VALUE; } String num = fileName.substring(fileName.lastIndexOf('.') + 1); return Long.parseLong(num); } @Override public String toString() { return String.format("%s:%d:%d", fileName, position, nextPosition); } @Override public int compareTo(@NonNull final BinlogFilePos other) { if (shouldCompareUsingFilePosition(this, other)) { return getFileNumber() != other.getFileNumber() ? Long.compare(getFileNumber(), other.getFileNumber()) : Long.compare(getPosition(), other.getPosition()); } if (this.gtidSet.equals(other.gtidSet)) { return 0; } if (this.gtidSet.isContainedWithin(other.gtidSet)) { return -1; } return 1; } /** Check if two BinlogFilePos are from the same source MySQL server */ private static boolean isFromSameSource(BinlogFilePos pos1, BinlogFilePos pos2) { return pos1.getServerUUID() != null && pos1.getServerUUID().equalsIgnoreCase(pos2.getServerUUID()); } /** Whether we can compare two BinlogFilePos using Binlog file position (without GTIDSet) */ public static boolean shouldCompareUsingFilePosition(BinlogFilePos pos1, BinlogFilePos pos2) { return isFromSameSource(pos1, pos2) || pos1.getGtidSet() == null || pos2.getGtidSet() == null; } public static Builder builder() { return new Builder(); } @JsonPOJOBuilder @NoArgsConstructor public static class Builder { private String fileName; private long position; private long nextPosition; private String gtidSet; private String serverUUID; public Builder withFileName(String fileName) { this.fileName = fileName; return this; } public Builder withPosition(long position) { this.position = position; return this; } public Builder withNextPosition(long nextPosition) { this.nextPosition = nextPosition; return this; } public Builder withGtidSet(String gtidSet) { this.gtidSet = gtidSet; return this; } public Builder withServerUUID(String serverUUID) { this.serverUUID = serverUUID; return this; } public BinlogFilePos build() { return new BinlogFilePos(fileName, position, nextPosition, gtidSet, serverUUID); } } }
2,003
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/GtidSet.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql; import com.fasterxml.jackson.annotation.JsonValue; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.TreeMap; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Value; /** This is an improvement of com.github.shyiko.mysql.binlog.GtidSet */ @EqualsAndHashCode public class GtidSet { private static final Splitter COMMA_SPLITTER = Splitter.on(','); private static final Splitter COLUMN_SPLITTER = Splitter.on(':'); private static final Splitter DASH_SPLITTER = Splitter.on('-'); private static final Joiner COMMA_JOINER = Joiner.on(','); private static final Joiner COLUMN_JOINER = Joiner.on(':'); // Use sorted map here so we can have a consistent GTID representation private final Map<String, UUIDSet> map = new TreeMap<>(); public GtidSet(String gtidSetString) { if (Strings.isNullOrEmpty(gtidSetString)) { return; } gtidSetString = gtidSetString.replaceAll("\n", "").replaceAll("\r", ""); for (String uuidSet : COMMA_SPLITTER.split(gtidSetString)) { Iterator<String> uuidSetIter = COLUMN_SPLITTER.split(uuidSet).iterator(); if (uuidSetIter.hasNext()) { String uuid = uuidSetIter.next().toLowerCase(); List<Interval> intervals = new LinkedList<>(); while (uuidSetIter.hasNext()) { Iterator<String> intervalIter = DASH_SPLITTER.split(uuidSetIter.next()).iterator(); if (intervalIter.hasNext()) { long start = Long.parseLong(intervalIter.next()); long end = intervalIter.hasNext() ? Long.parseLong(intervalIter.next()) : start; intervals.add(new Interval(start, end)); } } if (intervals.size() > 0) { if (map.containsKey(uuid)) { map.get(uuid).addIntervals(intervals); } else { map.put(uuid, new UUIDSet(uuid, intervals)); } } } } } public boolean isContainedWithin(GtidSet other) { if (other == null) { return false; } if (this.equals(other)) { return true; } for (UUIDSet uuidSet : map.values()) { UUIDSet thatSet = other.map.get(uuidSet.getUuid()); if (!uuidSet.isContainedWithin(thatSet)) { return false; } } return true; } @Override @JsonValue public String toString() { return COMMA_JOINER.join(map.values()); } @Getter @EqualsAndHashCode public static final class UUIDSet { private final String uuid; private final List<Interval> intervals; public UUIDSet(String uuid, List<Interval> intervals) { this.uuid = uuid.toLowerCase(); this.intervals = intervals; collapseIntervals(); } private void collapseIntervals() { Collections.sort(intervals); for (int i = intervals.size() - 1; i > 0; i--) { Interval before = intervals.get(i - 1); Interval after = intervals.get(i); if (after.getStart() <= before.getEnd() + 1) { if (after.getEnd() > before.getEnd()) { intervals.set(i - 1, new Interval(before.getStart(), after.getEnd())); } intervals.remove(i); } } } public void addIntervals(List<Interval> intervals) { this.intervals.addAll(intervals); collapseIntervals(); } public boolean isContainedWithin(UUIDSet other) { if (other == null) { return false; } if (!this.uuid.equals(other.uuid)) { return false; } if (this.intervals.isEmpty()) { return true; } if (other.intervals.isEmpty()) { return false; } // every interval in this must be within an interval of the other ... for (Interval thisInterval : this.intervals) { boolean found = false; for (Interval otherInterval : other.intervals) { if (thisInterval.isContainedWithin(otherInterval)) { found = true; break; } } if (!found) { return false; // didn't find a match } } return true; } @Override public String toString() { return uuid + ":" + COLUMN_JOINER.join(intervals); } } @Value public static class Interval implements Comparable<Interval> { long start, end; public boolean isContainedWithin(Interval other) { if (other == this) { return true; } if (other == null) { return false; } return this.start >= other.start && this.end <= other.end; } @Override public String toString() { return start + "-" + end; } @Override public int compareTo(Interval other) { if (this.start != other.start) { return Long.compare(this.start, other.start); } return Long.compare(this.end, other.end); } } }
2,004
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/Transaction.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql; import lombok.RequiredArgsConstructor; import lombok.Value; /** Represents a MySQL Transaction boundary in the binlog. */ @Value @RequiredArgsConstructor public class Transaction { private final long timestamp; private final long offset; private final BinlogFilePos position; private final String gtid; public Transaction(long timestamp, long offset, BinlogFilePos position) { this.timestamp = timestamp; this.offset = offset; this.position = position; this.gtid = null; } }
2,005
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/DataSource.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** Represents a MySQL data source configuration. */ @Getter @ToString @NoArgsConstructor @EqualsAndHashCode @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class DataSource { private String host; private int port; private String service; @JsonIgnore @Getter(lazy = true) private final com.airbnb.jitney.event.spinaltap.v1.DataSource thriftDataSource = toThriftDataSource(this); private static com.airbnb.jitney.event.spinaltap.v1.DataSource toThriftDataSource( DataSource dataSource) { return new com.airbnb.jitney.event.spinaltap.v1.DataSource( dataSource.getHost(), dataSource.getPort(), dataSource.getService()); } }
2,006
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/MysqlInsertMutation.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import java.util.Set; public final class MysqlInsertMutation extends MysqlMutation { public MysqlInsertMutation(MysqlMutationMetadata metadata, Row row) { super(metadata, Type.INSERT, row); } @Override public Set<String> getChangedColumns() { return getRow().getColumns().keySet(); } }
2,007
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/MysqlMutation.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import java.util.Set; import lombok.ToString; /** Represents a MySQL {@link Mutation} derived from a binlog event. */ @ToString(callSuper = true) public abstract class MysqlMutation extends Mutation<Row> { public MysqlMutation(MysqlMutationMetadata metadata, Mutation.Type type, Row row) { super(metadata, type, row); } public final Row getRow() { return getEntity(); } /** @return columns of the table that have changed value as a result of this mutation */ public abstract Set<String> getChangedColumns(); @Override public final MysqlMutationMetadata getMetadata() { return (MysqlMutationMetadata) super.getMetadata(); } }
2,008
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/MysqlMutationMetadata.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.mysql.BinlogFilePos; import com.airbnb.spinaltap.mysql.DataSource; import com.airbnb.spinaltap.mysql.Transaction; import com.airbnb.spinaltap.mysql.mutation.schema.Table; import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.Value; @Value @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) public class MysqlMutationMetadata extends Mutation.Metadata { private final DataSource dataSource; private final BinlogFilePos filePos; private final Table table; private final long serverId; private final Transaction beginTransaction; private final Transaction lastTransaction; /** The leader epoch of the node resource processing the event. */ private final long leaderEpoch; /** The mutation row position in the given binlog event. */ private final int eventRowPosition; public MysqlMutationMetadata( DataSource dataSource, BinlogFilePos filePos, Table table, long serverId, long id, long timestamp, Transaction beginTransaction, Transaction lastTransaction, long leaderEpoch, int eventRowPosition) { super(id, timestamp); this.dataSource = dataSource; this.filePos = filePos; this.table = table; this.serverId = serverId; this.beginTransaction = beginTransaction; this.lastTransaction = lastTransaction; this.leaderEpoch = leaderEpoch; this.eventRowPosition = eventRowPosition; } }
2,009
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/MysqlDeleteMutation.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import java.util.Set; public final class MysqlDeleteMutation extends MysqlMutation { public MysqlDeleteMutation(MysqlMutationMetadata metadata, Row row) { super(metadata, Mutation.Type.DELETE, row); } @Override public Set<String> getChangedColumns() { return getRow().getColumns().keySet(); } }
2,010
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/MysqlUpdateMutation.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.mysql.mutation.schema.Column; import com.airbnb.spinaltap.mysql.mutation.schema.Row; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import java.io.Serializable; import java.util.Map; import java.util.Set; import lombok.Getter; import lombok.NonNull; import lombok.ToString; @Getter @ToString(callSuper = true) public final class MysqlUpdateMutation extends MysqlMutation { private final Row previousRow; public MysqlUpdateMutation( final MysqlMutationMetadata metadata, final Row previousRow, final Row row) { super(metadata, Mutation.Type.UPDATE, row); this.previousRow = previousRow; } @Override public Set<String> getChangedColumns() { // Transform the column values of each Row to Map<String, Serializable>. Map values of type // byte[], or columns of type BLOB, will be tested for equality using deepEquals in method // getUpdatedColumns. If we simply passed down the Map<String, Column> of each Row, then // deepEquals would in turn call the equals method of type Column, which will wrongly not use // deepEquals to compare byte[] values. return Mutation.getUpdatedColumns(asColumnValues(getPreviousRow()), asColumnValues(getRow())); } @VisibleForTesting static Map<String, Serializable> asColumnValues(@NonNull final Row row) { return Maps.transformValues(row.getColumns(), Column::getValue); } }
2,011
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/ColumnMetadata.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.RequiredArgsConstructor; /** Represents additional metadata on a MySQL {@link Column}. */ @Data @RequiredArgsConstructor @AllArgsConstructor public class ColumnMetadata { private final String name; private final ColumnDataType colType; private final boolean isPrimaryKey; private final int position; private String rawColumnType; }
2,012
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/PrimaryKey.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import com.google.common.collect.ImmutableMap; import lombok.RequiredArgsConstructor; import lombok.Value; @Value @RequiredArgsConstructor public class PrimaryKey { /** Note: Insertion order should be preserved in the choice of {@link java.util.Map} implement. */ private final ImmutableMap<String, ColumnMetadata> columns; }
2,013
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/Row.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import com.google.common.collect.ImmutableMap; import lombok.Value; /** Represents a MySQL row. */ @Value public final class Row { private final Table table; private final ImmutableMap<String, Column> columns; @SuppressWarnings("unchecked") public <T> T getValue(final String columnName) { return (T) columns.get(columnName).getValue(); } public String getPrimaryKeyValue() { if (!table.getPrimaryKey().isPresent()) { return null; } final StringBuilder value = new StringBuilder(); table .getPrimaryKey() .get() .getColumns() .keySet() .stream() .map(columns::get) .map(Column::getValue) .forEach(value::append); return value.toString(); } public boolean containsColumn(final String columnName) { return columns.containsKey(columnName); } }
2,014
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/Table.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import com.airbnb.jitney.event.spinaltap.v1.Column; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import lombok.Getter; import lombok.Value; /** Represents a MySQL table. */ @Value public final class Table { private final long id; private final String name; private final String database; private final String overridingDatabase; /** * Note: It is important that the implement of the columns map retains the order of entry * insertion, as the sequence in which row columns in the binlog event are extracted is dependent * on it. {@code ImmutableMap} does retain the ordering. Any changes should should take this into * consideration */ private final ImmutableMap<String, ColumnMetadata> columns; private final Optional<PrimaryKey> primaryKey; @Getter(lazy = true) private final com.airbnb.jitney.event.spinaltap.v1.Table thriftTable = toThriftTable(this); public Table( long id, String name, String database, List<ColumnMetadata> columnMetadatas, List<String> primaryKeyColumns) { this(id, name, database, null, columnMetadatas, primaryKeyColumns); } public Table( long id, String name, String database, String overridingDatabase, List<ColumnMetadata> columnMetadatas, List<String> primaryKeyColumns) { this.id = id; this.name = name; this.database = database; this.overridingDatabase = overridingDatabase; this.columns = createColumns(columnMetadatas); this.primaryKey = createPrimaryKey(primaryKeyColumns, columns); } public static com.airbnb.jitney.event.spinaltap.v1.Table toThriftTable(Table table) { Set<String> primaryKey = ImmutableSet.of(); if (table.getPrimaryKey().isPresent()) { primaryKey = ImmutableSet.copyOf( table .getPrimaryKey() .get() .getColumns() .values() .stream() .map(ColumnMetadata::getName) .sorted() .collect(Collectors.toList())); } Map<String, Column> columns = table .getColumns() .values() .stream() .map( c -> { com.airbnb.jitney.event.spinaltap.v1.Column column = new com.airbnb.jitney.event.spinaltap.v1.Column( c.getColType().getCode(), c.isPrimaryKey(), c.getName()); column.setPosition(c.getPosition()); return column; }) .collect(Collectors.toMap(c -> c.getName(), c -> c)); com.airbnb.jitney.event.spinaltap.v1.Table thriftTable = new com.airbnb.jitney.event.spinaltap.v1.Table( table.getId(), table.getName(), table.getDatabase(), primaryKey, columns); if (!Strings.isNullOrEmpty(table.getOverridingDatabase())) { thriftTable.setOverridingDatabase(table.getOverridingDatabase()); } return thriftTable; } public static String canonicalNameOf(String db, String tableName) { return String.format("%s:%s", db, tableName); } public static Set<String> getDatabaseNames(Collection<String> canonicalTableNames) { Set<String> databaseNames = Sets.newHashSet(); canonicalTableNames.forEach( canonicalTableName -> { String databaseName = Splitter.on(':').split(canonicalTableName).iterator().next(); databaseNames.add(databaseName); }); return databaseNames; } public String getCanonicalName() { return canonicalNameOf(database, name); } private static Optional<PrimaryKey> createPrimaryKey( List<String> pkColumnNames, ImmutableMap<String, ColumnMetadata> columns) { if (pkColumnNames.isEmpty()) { return Optional.absent(); } ImmutableMap.Builder<String, ColumnMetadata> builder = ImmutableMap.builder(); for (String colName : pkColumnNames) { builder.put(colName, columns.get(colName)); } return Optional.of(new PrimaryKey(builder.build())); } private static ImmutableMap<String, ColumnMetadata> createColumns( List<ColumnMetadata> columnMetadatas) { ImmutableMap.Builder<String, ColumnMetadata> builder = ImmutableMap.builder(); for (ColumnMetadata col : columnMetadatas) { builder.put(col.getName(), col); } return builder.build(); } }
2,015
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/Column.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import java.io.Serializable; import lombok.Value; /** Represents a MySQL column. */ @Value public class Column { private final ColumnMetadata metadata; private final Serializable value; }
2,016
0
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation
Create_ds/SpinalTap/spinaltap-model/src/main/java/com/airbnb/spinaltap/mysql/mutation/schema/ColumnDataType.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.mysql.mutation.schema; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import lombok.Getter; import lombok.RequiredArgsConstructor; /** An enumeration of the supported data types for a MySQL {@link Column}. */ @RequiredArgsConstructor public enum ColumnDataType { DECIMAL(0), TINY(1), SHORT(2), LONG(3), FLOAT(4), DOUBLE(5), NULL(6), TIMESTAMP(7), LONGLONG(8), INT24(9), DATE(10), TIME(11), DATETIME(12), YEAR(13), NEWDATE(14), VARCHAR(15), BIT(16), // (TIMESTAMP|DATETIME|TIME)_V2 data types appeared in MySQL 5.6.4 // @see http://dev.mysql.com/doc/internals/en/date-and-time-data-type-representation.html TIMESTAMP_V2(17), DATETIME_V2(18), TIME_V2(19), NEWDECIMAL(246), ENUM(247), SET(248), TINY_BLOB(249), MEDIUM_BLOB(250), LONG_BLOB(251), BLOB(252), VAR_STRING(253), STRING(254), GEOMETRY(255), // TODO: Remove UNKNOWN. This is known finite list of types. Any other value is not valid. // Treating this case as an error (throwing exception etc) is better. UNKNOWN(-1); @Getter private final int code; private static final Map<Integer, ColumnDataType> INDEX_BY_CODE = Stream.of(values()).collect(Collectors.toMap(ColumnDataType::getCode, Function.identity())); /** * The Java type is an 8-bit signed two's complement integer. But MySql byte is not. So when * looking up the column type from a MySql byte, it must be upcast to an int first. * * <p>As an example, let's take BLOB/252. Mysql column type will be the byte 0b11111100. If casted * to a java integer it will be interpreted as -4. * * <p>Integer.toBinaryString((int)((byte) 252)): '11111111111111111111111111111100' */ public static ColumnDataType byCode(final byte code) { return byCode(code & 0xFF); } public static ColumnDataType byCode(final int code) { return INDEX_BY_CODE.getOrDefault(code, UNKNOWN); } }
2,017
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/pipe/PipeTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.destination.Destination; import com.airbnb.spinaltap.common.source.Source; import org.junit.Before; import org.junit.Test; public class PipeTest { private final Source source = mock(Source.class); private final Destination destination = mock(Destination.class); private final PipeMetrics metrics = mock(PipeMetrics.class); private final Mutation lastMutation = mock(Mutation.class); private final Pipe pipe = new Pipe(source, destination, metrics); @Before public void setUp() throws Exception { when(destination.getLastPublishedMutation()).thenReturn(lastMutation); } @Test public void testStartStop() throws Exception { Mutation mutation = mock(Mutation.class); Mutation.Metadata metadata = mock(Mutation.Metadata.class); when(destination.getLastPublishedMutation()).thenReturn(mutation); when(mutation.getMetadata()).thenReturn(metadata); pipe.start(); when(source.isStarted()).thenReturn(true); when(destination.isStarted()).thenReturn(true); verify(source, times(1)).addListener(any(Source.Listener.class)); verify(source, times(1)).open(); verify(destination, times(1)).addListener(any(Destination.Listener.class)); verify(destination, times(1)).open(); verify(metrics, times(1)).open(); pipe.stop(); verify(source, times(1)).removeListener(any(Source.Listener.class)); verify(source, times(1)).checkpoint(mutation); verify(source, times(1)).close(); verify(destination, times(1)).removeListener(any(Destination.Listener.class)); verify(destination, times(1)).close(); verify(metrics, times(1)).close(); } @Test public void testIsStarted() throws Exception { when(source.isStarted()).thenReturn(true); when(destination.isStarted()).thenReturn(false); assertFalse(pipe.isStarted()); when(source.isStarted()).thenReturn(false); when(destination.isStarted()).thenReturn(true); assertFalse(pipe.isStarted()); when(source.isStarted()).thenReturn(true); when(destination.isStarted()).thenReturn(true); assertTrue(pipe.isStarted()); } @Test public void testCheckpoint() throws Exception { pipe.checkpoint(); verify(source, times(1)).checkpoint(lastMutation); } }
2,018
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/pipe/PipeManagerTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.google.common.collect.ImmutableList; import org.junit.Test; public class PipeManagerTest { private static final String NAME = "test"; private static final String PARTITION = "test_0"; private final Pipe firstPipe = mock(Pipe.class); private final Pipe secondPipe = mock(Pipe.class); @Test public void testAddRemovePipe() throws Exception { PipeManager pipeManager = new PipeManager(); pipeManager.addPipes(NAME, PARTITION, ImmutableList.of(firstPipe, secondPipe)); verify(firstPipe, times(1)).start(); verify(secondPipe, times(1)).start(); pipeManager.removePipe(NAME, PARTITION); verify(firstPipe, times(1)).stop(); verify(secondPipe, times(1)).stop(); assertTrue(pipeManager.isEmpty()); } }
2,019
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/validator/MutationOrderValidatorTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.validator; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.airbnb.spinaltap.Mutation; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; public class MutationOrderValidatorTest { private final Mutation firstMutation = mock(Mutation.class); private final Mutation secondMutation = mock(Mutation.class); private final Mutation.Metadata firstMetadata = mock(Mutation.Metadata.class); private final Mutation.Metadata secondMetadata = mock(Mutation.Metadata.class); @Before public void setUp() throws Exception { when(firstMutation.getMetadata()).thenReturn(firstMetadata); when(secondMutation.getMetadata()).thenReturn(secondMetadata); } @Test public void testMutationInOrder() throws Exception { List<Mutation> unorderedMutations = Lists.newArrayList(); when(firstMetadata.getId()).thenReturn(1L); when(secondMetadata.getId()).thenReturn(2L); MutationOrderValidator validator = new MutationOrderValidator(unorderedMutations::add); validator.validate(firstMutation); validator.validate(secondMutation); assertTrue(unorderedMutations.isEmpty()); } @Test public void testMutationOutOfOrder() throws Exception { List<Mutation> unorderedMutations = Lists.newArrayList(); when(firstMetadata.getId()).thenReturn(2L); when(secondMetadata.getId()).thenReturn(1L); MutationOrderValidator validator = new MutationOrderValidator(unorderedMutations::add); validator.validate(firstMutation); validator.validate(secondMutation); assertEquals(Arrays.asList(secondMutation), unorderedMutations); } @Test public void testReset() throws Exception { List<Mutation> unorderedMutations = Lists.newArrayList(); when(firstMetadata.getId()).thenReturn(1L); when(secondMetadata.getId()).thenReturn(2L); MutationOrderValidator validator = new MutationOrderValidator(unorderedMutations::add); validator.validate(firstMutation); validator.validate(secondMutation); validator.reset(); validator.validate(firstMutation); validator.validate(secondMutation); assertTrue(unorderedMutations.isEmpty()); } }
2,020
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/util/ClassBasedMapperTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ClassBasedMapperTest { @Test public void testMap() throws Exception { Mapper<Object, Integer> mapper = ClassBasedMapper.<Object, Integer>builder() .addMapper(Float.class, Math::round) .addMapper(String.class, Integer::parseInt) .build(); assertEquals(new Integer(1), mapper.map(new Float(1.2))); assertEquals(new Integer(3), mapper.map("3")); } @Test(expected = IllegalStateException.class) public void testNoMapFound() throws Exception { ClassBasedMapper.<Object, Integer>builder().build().map(1); } }
2,021
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/util/ChainedFilterTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; public class ChainedFilterTest { @Test public void testFailingFilter() throws Exception { Filter<Integer> filter = ChainedFilter.<Integer>builder().addFilter(num -> true).addFilter(num -> false).build(); assertFalse(filter.apply(1)); } @Test public void testPassingFilter() throws Exception { Filter<Integer> filter = ChainedFilter.<Integer>builder().addFilter(num -> true).addFilter(num -> true).build(); assertTrue(filter.apply(1)); } @Test public void testEmptyFilter() throws Exception { Filter<Integer> filter = ChainedFilter.<Integer>builder().build(); assertTrue(filter.apply(1)); } }
2,022
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/source/ListenableSourceTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import com.airbnb.spinaltap.Mutation; import org.junit.Test; public class ListenableSourceTest { private final Source.Listener listener = mock(Source.Listener.class); private ListenableSource<SourceEvent> source = new TestListenableSource(); @Test public void test() throws Exception { Exception exception = mock(Exception.class); SourceEvent event = mock(SourceEvent.class); source.addListener(listener); source.notifyStart(); source.notifyEvent(event); source.notifyError(exception); verify(listener).onStart(); verify(listener).onEvent(event); verify(listener).onError(exception); source.removeListener(listener); source.notifyStart(); source.notifyEvent(event); source.notifyError(exception); verifyNoMoreInteractions(listener); } private static final class TestListenableSource extends ListenableSource<SourceEvent> { @Override public String getName() { return null; } @Override public boolean isStarted() { return false; } @Override public void open() {} @Override public void close() {} @Override public void clear() {} @Override public void checkpoint(Mutation<?> mutation) {} } }
2,023
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/source/AbstractSourceTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.exception.SourceException; import com.airbnb.spinaltap.common.util.Filter; import com.airbnb.spinaltap.common.util.Mapper; import java.util.Collections; import java.util.List; import lombok.Getter; import lombok.Setter; import org.junit.Before; import org.junit.Test; public class AbstractSourceTest { private final SourceMetrics metrics = mock(SourceMetrics.class); private final SourceEvent event = mock(SourceEvent.class); private final Mapper<SourceEvent, List<? extends Mutation<?>>> mapper = mock(Mapper.class); private final Filter<SourceEvent> filter = mock(Filter.class); private final Source.Listener listener = mock(Source.Listener.class); private TestSource source; @Before public void setUp() throws Exception { source = new TestSource(metrics); source.addListener(listener); } @Test public void testOpenClose() throws Exception { source.open(); assertTrue(source.isStarted()); verify(metrics, times(1)).start(); source.open(); assertTrue(source.isStarted()); verify(metrics, times(1)).start(); source.close(); assertFalse(source.isStarted()); verify(metrics, times(1)).stop(); source.close(); assertFalse(source.isStarted()); verify(metrics, times(2)).stop(); } @Test(expected = SourceException.class) public void testOpenFailure() throws Exception { source.setStarted(false); source.setFailStart(true); try { source.open(); } catch (RuntimeException ex) { verify(metrics, times(1)).startFailure(any(RuntimeException.class)); verify(metrics, times(1)).stop(); throw ex; } } @Test public void testProcessEvent() throws Exception { List mutations = Collections.singletonList(mock(Mutation.class)); when(mapper.map(event)).thenReturn(mutations); when(filter.apply(event)).thenReturn(false); source.processEvent(event); verifyZeroInteractions(metrics); verify(listener, times(0)).onMutation(mutations); when(filter.apply(event)).thenReturn(true); source.processEvent(event); verify(listener, times(1)).onMutation(mutations); when(mapper.map(event)).thenReturn(Collections.emptyList()); source.processEvent(event); verify(listener, times(2)).onEvent(event); verify(metrics, times(2)).eventReceived(event); verify(listener, times(1)).onMutation(mutations); } @Test(expected = SourceException.class) public void testProcessEventFailure() throws Exception { RuntimeException testException = new RuntimeException(); when(filter.apply(event)).thenThrow(testException); source.setStarted(false); source.processEvent(event); verify(listener, times(0)).onMutation(any()); verify(metrics, times(0)).eventFailure(testException); verify(listener, times(0)).onError(testException); source.setStarted(true); source.processEvent(event); verify(listener, times(0)).onMutation(any()); verify(metrics, times(1)).eventFailure(testException); verify(listener, times(1)).onError(testException); } @Test(expected = SourceException.class) public void testOpenWhilePreviousProcessorRunning() throws Exception { source.open(); source.setStarted(false); source.open(); } @Getter @Setter class TestSource extends AbstractSource<SourceEvent> { private boolean started = false; private boolean terminated = true; private boolean failStart; private boolean failStop; public TestSource(SourceMetrics metrics) { super("test", metrics, mapper, filter); } public void commitCheckpoint(Mutation metadata) {} @Override public boolean isStarted() { return isRunning(); } @Override protected boolean isRunning() { return started; } @Override protected boolean isTerminated() { return terminated; } @Override public void start() { if (failStart) { throw new RuntimeException(); } started = true; terminated = false; } @Override public void stop() { if (failStop) { throw new RuntimeException(); } started = false; terminated = true; } @Override protected void initialize() {} } }
2,024
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/destination/DestinationPoolTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.KeyProvider; import com.google.common.collect.ImmutableList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import lombok.NoArgsConstructor; import org.junit.Test; public class DestinationPoolTest { private final Destination firstDestination = mock(Destination.class); private final Destination secondDestination = mock(Destination.class); private final Destination thirdDestination = mock(Destination.class); private final Destination fourthDestination = mock(Destination.class); private final KeyProvider<Mutation<?>, String> keyProvider = mock(KeyProvider.class); private final List<Destination> destinations = Arrays.asList(firstDestination, secondDestination, thirdDestination, fourthDestination); private final DestinationPool destinationPool = new DestinationPool(keyProvider, destinations); @Test public void testOpenClose() throws Exception { Destination destination1 = new TestDestination(); Destination destination2 = new TestDestination(); DestinationPool testDestinationPool = new DestinationPool(keyProvider, ImmutableList.of(destination1, destination2)); testDestinationPool.open(); assertTrue(testDestinationPool.isStarted()); assertTrue(destination1.isStarted()); assertTrue(destination2.isStarted()); testDestinationPool.close(); assertFalse(testDestinationPool.isStarted()); assertFalse(destination1.isStarted()); assertFalse(destination2.isStarted()); } @Test public void testIsOpen() throws Exception { when(firstDestination.isStarted()).thenReturn(true); when(secondDestination.isStarted()).thenReturn(true); when(thirdDestination.isStarted()).thenReturn(true); when(fourthDestination.isStarted()).thenReturn(false); assertFalse(destinationPool.isStarted()); when(fourthDestination.isStarted()).thenReturn(true); assertTrue(destinationPool.isStarted()); } @Test public void testSend() throws Exception { Mutation<?> firstMutation = mock(Mutation.class); Mutation<?> secondMutation = mock(Mutation.class); Mutation<?> thirdMutation = mock(Mutation.class); Mutation<?> fourthMutation = mock(Mutation.class); Mutation<?> fifthMutation = mock(Mutation.class); Mutation.Metadata firstMetadata = mock(Mutation.Metadata.class); Mutation.Metadata secondMetadata = mock(Mutation.Metadata.class); Mutation.Metadata thirdMetadata = mock(Mutation.Metadata.class); when(firstMetadata.getId()).thenReturn(3L); when(secondMetadata.getId()).thenReturn(2L); when(thirdMetadata.getId()).thenReturn(4L); when(firstMutation.getMetadata()).thenReturn(firstMetadata); when(secondMutation.getMetadata()).thenReturn(secondMetadata); when(thirdMutation.getMetadata()).thenReturn(thirdMetadata); when(keyProvider.get(firstMutation)).thenReturn("4"); when(keyProvider.get(secondMutation)).thenReturn("6"); when(keyProvider.get(thirdMutation)).thenReturn("9"); when(keyProvider.get(fourthMutation)).thenReturn("2"); when(keyProvider.get(fifthMutation)).thenReturn("1"); assertEquals(null, firstDestination.getLastPublishedMutation()); destinationPool.send( Arrays.asList(firstMutation, secondMutation, thirdMutation, fourthMutation, fifthMutation)); verify(firstDestination, times(1)).send(Collections.singletonList(firstMutation)); verify(secondDestination, times(1)).send(ImmutableList.of(thirdMutation, fifthMutation)); verify(thirdDestination, times(1)).send(ImmutableList.of(secondMutation, fourthMutation)); when(firstDestination.getLastPublishedMutation()).thenReturn((Mutation) firstMutation); when(secondDestination.getLastPublishedMutation()).thenReturn((Mutation) thirdMutation); when(thirdDestination.getLastPublishedMutation()).thenReturn((Mutation) secondMutation); when(fourthDestination.getLastPublishedMutation()).thenReturn(null); assertEquals(secondMutation, destinationPool.getLastPublishedMutation()); when(firstDestination.getLastPublishedMutation()).thenReturn(null); assertEquals(null, destinationPool.getLastPublishedMutation()); } @Test public void testSendFailure() throws Exception { Destination corruptDestination = new TestDestination(); Mutation<?> firstMutation = mock(Mutation.class); Mutation<?> secondMutation = mock(Mutation.class); when(keyProvider.get(firstMutation)).thenReturn("0"); when(keyProvider.get(secondMutation)).thenReturn("1"); Destination.Listener listener = mock(Destination.Listener.class); DestinationPool pool = new DestinationPool( keyProvider, Arrays.asList(mock(Destination.class), corruptDestination)); pool.addListener(listener); pool.send(ImmutableList.of(firstMutation, secondMutation)); verify(listener, times(1)).onError(any(RuntimeException.class)); } @NoArgsConstructor class TestDestination extends ListenableDestination { private AtomicBoolean isStarted = new AtomicBoolean(); private AtomicBoolean isCleared = new AtomicBoolean(); public Mutation<?> getLastPublishedMutation() { return null; } @Override public void send(List<? extends Mutation<?>> mutations) { notifyError(new RuntimeException()); } @Override public boolean isStarted() { return isStarted.get(); } @Override public void open() { isStarted.set(true); } @Override public void close() { isStarted.set(false); } @Override public void clear() { isCleared.set(true); } } }
2,025
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/destination/BufferedDestinationTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.airbnb.spinaltap.Mutation; import com.google.common.collect.ImmutableList; import java.util.List; import org.junit.Before; import org.junit.Test; public class BufferedDestinationTest { private final Mutation<?> firstMutation = mock(Mutation.class); private final Mutation<?> secondMutation = mock(Mutation.class); private final Mutation<?> thirdMutation = mock(Mutation.class); private final List<Mutation<?>> mutations = ImmutableList.of(firstMutation, secondMutation, thirdMutation); private final Destination destination = mock(Destination.class); private final Destination.Listener listener = mock(Destination.Listener.class); private final DestinationMetrics metrics = mock(DestinationMetrics.class); private BufferedDestination bufferedDestination = new BufferedDestination("test", 10, destination, metrics); @Before public void setUp() throws Exception { bufferedDestination.addListener(listener); } @Test public void testOpenClose() throws Exception { when(destination.isStarted()).thenReturn(false); bufferedDestination.open(); when(destination.isStarted()).thenReturn(true); assertTrue(bufferedDestination.isStarted()); verify(destination).open(); bufferedDestination.open(); assertTrue(bufferedDestination.isStarted()); verify(destination).open(); bufferedDestination.close(); verify(destination).close(); } @Test public void testSend() throws Exception { when(destination.isStarted()).thenReturn(true); bufferedDestination.send(ImmutableList.of(firstMutation, secondMutation)); bufferedDestination.processMutations(); verify(destination).send(ImmutableList.of(firstMutation, secondMutation)); bufferedDestination.send(ImmutableList.of(firstMutation)); bufferedDestination.send(ImmutableList.of(secondMutation, thirdMutation)); bufferedDestination.processMutations(); verify(destination).send(mutations); } }
2,026
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/destination/ListenableDestinationTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import com.airbnb.spinaltap.Mutation; import com.google.common.collect.ImmutableList; import java.util.List; import org.junit.Test; public class ListenableDestinationTest { private final Destination.Listener listener = mock(Destination.Listener.class); private ListenableDestination destination = new TestListenableDestination(); @Test public void test() throws Exception { Exception exception = mock(Exception.class); List<Mutation<?>> mutations = ImmutableList.of(mock(Mutation.class)); destination.addListener(listener); destination.notifyStart(); destination.notifySend(mutations); destination.notifyError(exception); verify(listener).onStart(); verify(listener).onSend(mutations); verify(listener).onError(exception); destination.removeListener(listener); destination.notifyStart(); destination.notifySend(mutations); destination.notifyError(exception); verifyNoMoreInteractions(listener); } private static final class TestListenableDestination extends ListenableDestination { @Override public Mutation<?> getLastPublishedMutation() { return null; } @Override public void send(List<? extends Mutation<?>> mutations) {} @Override public boolean isStarted() { return false; } @Override public void close() {} @Override public void clear() {} } }
2,027
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/destination/AbstractDestinationTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.exception.DestinationException; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import java.util.List; import lombok.Getter; import lombok.Setter; import org.junit.Before; import org.junit.Test; public class AbstractDestinationTest { private final Destination.Listener listener = mock(Destination.Listener.class); private final DestinationMetrics metrics = mock(DestinationMetrics.class); private final Mutation<?> firstMutation = mock(Mutation.class); private final Mutation<?> secondMutation = mock(Mutation.class); private final Mutation<?> thirdMutation = mock(Mutation.class); private final List<Mutation<?>> mutations = ImmutableList.of(firstMutation, secondMutation, thirdMutation); private TestDestination destination; @Before public void setUp() throws Exception { destination = new TestDestination(); destination.addListener(listener); } @Test public void testSend() throws Exception { Mutation.Metadata metadata = mock(Mutation.Metadata.class); when(firstMutation.getMetadata()).thenReturn(metadata); when(secondMutation.getMetadata()).thenReturn(metadata); when(thirdMutation.getMetadata()).thenReturn(metadata); when(metadata.getTimestamp()).thenReturn(0L); destination.send(mutations); assertEquals(3, destination.getPublishedMutations()); assertEquals(thirdMutation, destination.getLastPublishedMutation()); verify(metrics).publishSucceeded(mutations); verify(listener).onSend(mutations); } @Test public void testSendEmptyMutationList() throws Exception { destination.send(ImmutableList.of()); assertEquals(0, destination.getPublishedMutations()); assertNull(destination.getLastPublishedMutation()); verifyZeroInteractions(metrics); } @Test(expected = DestinationException.class) public void testSendFailure() throws Exception { Mutation.Metadata metadata = mock(Mutation.Metadata.class); when(firstMutation.getMetadata()).thenReturn(metadata); when(metadata.getTimestamp()).thenReturn(0L); destination.setFailPublish(true); try { destination.send(ImmutableList.of(firstMutation, secondMutation)); } catch (Exception ex) { assertNull(destination.getLastPublishedMutation()); verify(metrics, times(2)).publishFailed(any(Mutation.class), any(RuntimeException.class)); throw ex; } } @Test public void testOpen() throws Exception { Mutation.Metadata metadata = mock(Mutation.Metadata.class); when(firstMutation.getMetadata()).thenReturn(metadata); when(metadata.getTimestamp()).thenReturn(0L); destination.send(ImmutableList.of(firstMutation)); assertEquals(firstMutation, destination.getLastPublishedMutation()); destination.open(); assertNull(destination.getLastPublishedMutation()); verify(listener, times(1)).onStart(); } class TestDestination extends AbstractDestination<Mutation<?>> { @Getter private int publishedMutations; @Setter private boolean failPublish; public TestDestination() { super(m -> m, metrics, 0L); } @Override public boolean isStarted() { return true; } @VisibleForTesting @Override public void publish(List<Mutation<?>> MUTATIONS) { if (failPublish) { throw new RuntimeException(); } publishedMutations += MUTATIONS.size(); } } }
2,028
0
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/test/java/com/airbnb/spinaltap/common/destination/DestinationBuilderTest.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.KeyProvider; import com.airbnb.spinaltap.common.util.Mapper; import lombok.NoArgsConstructor; import org.junit.Test; public class DestinationBuilderTest { private static final Mapper<Mutation<?>, Mutation<?>> mapper = mutation -> mutation; private static final DestinationMetrics metrics = new DestinationMetrics("test", "test", new TaggedMetricRegistry()); @Test(expected = NullPointerException.class) public void testNoMapper() throws Exception { new TestDestinationBuilder().withMetrics(metrics).build(); } @Test(expected = NullPointerException.class) public void testNoMetrics() throws Exception { new TestDestinationBuilder().withMapper(mapper).build(); } @Test public void testBuildBufferedDestination() throws Exception { Destination destination = new TestDestinationBuilder().withMapper(mapper).withMetrics(metrics).withBuffer(5).build(); assertTrue(destination instanceof BufferedDestination); assertEquals(5, ((BufferedDestination) destination).getRemainingCapacity()); } @Test public void testBuildDestinationPool() throws Exception { Destination destination = new TestDestinationBuilder() .withMapper(mapper) .withMetrics(metrics) .withBuffer(5) .withPool(7, mock(KeyProvider.class)) .build(); assertTrue(destination instanceof DestinationPool); assertEquals(7, ((DestinationPool) destination).getPoolSize()); } @NoArgsConstructor class TestDestinationBuilder extends DestinationBuilder<Mutation<?>> { @Override protected Destination createDestination() { return mock(Destination.class); } } }
2,029
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/metrics/SpinalTapMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.metrics; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.source.SourceEvent; import com.codahale.metrics.Gauge; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.util.Collections; import java.util.HashMap; import java.util.Map; import lombok.RequiredArgsConstructor; /** Base class for metrics collection. */ @RequiredArgsConstructor public abstract class SpinalTapMetrics { protected static final String METRIC_PREFIX = "spinaltap"; protected static final String ERROR_TAG = "error"; protected static final String EVENT_TYPE_TAG = "event_type"; protected static final String MUTATION_TYPE_TAG = "mutation_type"; protected static final String HOST_NAME_TAG = "host_name"; protected static final String SERVER_NAME_TAG = "server_name"; public static final String DATABASE_NAME_TAG = "database_name"; public static final String TABLE_NAME_TAG = "table_name"; public static final String TOPIC_NAME_TAG = "topic_name"; public static final String RESOURCE_NAME_TAG = "resource_name"; public static final String INSTANCE_NAME_TAG = "instance_name"; public static final String DATA_STORE_TYPE_TAG = "data_store_type"; public static final String SOURCE_TYPE_TAG = "source_type"; public static final String SOURCE_NAME_TAG = "source_name"; private final ImmutableMap<String, String> defaultTags; private final TaggedMetricRegistry metricRegistry; public SpinalTapMetrics(TaggedMetricRegistry metricRegistry) { this(ImmutableMap.of(), metricRegistry); } protected void registerGauge(String metricName, Gauge<?> gauge) { registerGauge(metricName, gauge, Collections.emptyMap()); } protected void registerGauge(String metricName, Gauge<?> gauge, Map<String, String> tags) { // Remove the old gauge from the registry if it exists, since we // cannot register a new gauge if the key already is present removeGauge(metricName, tags); Map<String, String> allTags = new HashMap<>(); allTags.putAll(defaultTags); allTags.putAll(tags); metricRegistry.<Gauge<?>>register(metricName, allTags, gauge); } protected void removeGauge(String metricName) { removeGauge(metricName, Collections.emptyMap()); } protected void removeGauge(String metricName, Map<String, String> tags) { Map<String, String> allTags = new HashMap<>(); allTags.putAll(defaultTags); allTags.putAll(tags); metricRegistry.remove(metricName, allTags); } protected void incError(String metricName, Throwable error) { incError(metricName, error, Collections.emptyMap()); } protected void incError(String metricName, Throwable error, Map<String, String> tags) { Map<String, String> errorTags = Maps.newHashMap(); errorTags.put(ERROR_TAG, error.getClass().toString()); errorTags.putAll(tags); inc(metricName, errorTags); } protected void inc(String metricName) { inc(metricName, Collections.emptyMap()); } protected void inc(String metricName, Map<String, String> tags) { inc(metricName, tags, 1); } protected void inc(String metricName, Map<String, String> tags, int count) { Map<String, String> allTags = Maps.newHashMap(); allTags.putAll(defaultTags); allTags.putAll(tags); metricRegistry.counter(metricName, allTags).inc(count); } protected void update(String metricName, long value) { update(metricName, value, Collections.emptyMap()); } protected void update(String metricName, long value, Map<String, String> tags) { Map<String, String> allTags = Maps.newHashMap(); allTags.putAll(defaultTags); allTags.putAll(tags); metricRegistry.histogram(metricName, allTags).update(value); } protected Map<String, String> getTags(SourceEvent event) { Map<String, String> eventTags = new HashMap<>(); eventTags.putAll(defaultTags); eventTags.put(EVENT_TYPE_TAG, event.getClass().getSimpleName()); return eventTags; } protected Map<String, String> getTags(Mutation<?> mutation) { Map<String, String> mutationTags = Maps.newHashMap(); mutationTags.putAll(getTags(mutation.getMetadata())); mutationTags.put(MUTATION_TYPE_TAG, mutation.getType().toString()); return mutationTags; } protected Map<String, String> getTags(Mutation.Metadata metadata) { return Collections.emptyMap(); } public void clear() {} }
2,030
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/pipe/PipeMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.common.metrics.SpinalTapMetrics; import com.google.common.collect.ImmutableMap; /** Responsible for metrics collection for a {@link Pipe}. */ public class PipeMetrics extends SpinalTapMetrics { private static final String PIPE_PREFIX = METRIC_PREFIX + ".pipe"; private static final String OPEN_METRIC = PIPE_PREFIX + ".open.count"; private static final String CLOSE_METRIC = PIPE_PREFIX + ".close.count"; private static final String START_METRIC = PIPE_PREFIX + ".start.count"; private static final String STOP_METRIC = PIPE_PREFIX + ".stop.count"; private static final String CHECKPOINT_METRIC = PIPE_PREFIX + ".checkpoint.count"; public PipeMetrics(String sourceName, TaggedMetricRegistry metricRegistry) { this(ImmutableMap.of(SOURCE_NAME_TAG, sourceName), metricRegistry); } public PipeMetrics(ImmutableMap<String, String> tags, TaggedMetricRegistry metricRegistry) { super(tags, metricRegistry); } public void open() { inc(OPEN_METRIC); } public void close() { inc(CLOSE_METRIC); } public void start() { inc(START_METRIC); } public void stop() { inc(STOP_METRIC); } public void checkpoint() { inc(CHECKPOINT_METRIC); } }
2,031
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/pipe/AbstractPipeFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.common.config.SourceConfiguration; import com.airbnb.spinaltap.common.source.SourceState; import com.airbnb.spinaltap.common.util.StateRepositoryFactory; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public abstract class AbstractPipeFactory<S extends SourceState, T extends SourceConfiguration> { private static String HOST_NAME = "unknown"; protected final TaggedMetricRegistry metricRegistry; public abstract List<Pipe> createPipes( T sourceConfig, String partitionName, StateRepositoryFactory<S> repositoryFactory, long leaderEpoch) throws Exception; protected static String getHostName() { if ("unknown".equalsIgnoreCase(HOST_NAME)) { try { HOST_NAME = InetAddress.getLocalHost().getCanonicalHostName(); } catch (UnknownHostException e) { log.error("Could not retrieve host name", e); } } return HOST_NAME; } }
2,032
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/pipe/Pipe.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.destination.Destination; import com.airbnb.spinaltap.common.source.Source; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Responsible for managing event streaming from a {@link com.airbnb.spinaltap.common.source.Source} * to a given {@link com.airbnb.spinaltap.common.destination.Destination}, as well as the lifecycle * of both components. */ @Slf4j @RequiredArgsConstructor public class Pipe { private static final int CHECKPOINT_PERIOD_SECONDS = 60; private static final int KEEP_ALIVE_PERIOD_SECONDS = 5; private static final int EXECUTOR_DELAY_SECONDS = 5; @NonNull @Getter private final Source source; @NonNull private final Destination destination; @NonNull private final PipeMetrics metrics; private final Source.Listener sourceListener = new SourceListener(); private final Destination.Listener destinationListener = new DestinationListener(); /** The checkpoint executor that periodically checkpoints the state of the source. */ private ExecutorService checkpointExecutor; /** * The keep-alive executor that periodically checks the pipe is alive, and otherwise restarts it. */ private ExecutorService keepAliveExecutor; /** The error-handling executor that executes error-handling procedurewhen error occurred. */ private ExecutorService errorHandlingExecutor; /** @return The name of the pipe. */ public String getName() { return source.getName(); } /** @return the last mutation successfully sent to the pipe's {@link Destination}. */ public Mutation<?> getLastMutation() { return destination.getLastPublishedMutation(); } /** Starts event streaming for the pipe. */ public void start() { source.addListener(sourceListener); destination.addListener(destinationListener); open(); scheduleKeepAliveExecutor(); scheduleCheckpointExecutor(); errorHandlingExecutor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setNameFormat(getName() + "-error-handling-executor") .build()); metrics.start(); } private void scheduleKeepAliveExecutor() { if (keepAliveExecutor != null && !keepAliveExecutor.isShutdown()) { log.debug("Keep-alive executor is running"); return; } String name = getName() + "-pipe-keep-alive-executor"; keepAliveExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(name).build()); keepAliveExecutor.execute( () -> { try { Thread.sleep(EXECUTOR_DELAY_SECONDS * 1000); } catch (InterruptedException ex) { log.info("{} is interrupted.", name); } while (!keepAliveExecutor.isShutdown()) { try { if (isStarted()) { log.info("Pipe {} is alive", getName()); } else { open(); } } catch (Exception ex) { log.error("Failed to open pipe " + getName(), ex); } try { Thread.sleep(KEEP_ALIVE_PERIOD_SECONDS * 1000); } catch (InterruptedException ex) { log.info("{} is interrupted.", name); } } }); } private void scheduleCheckpointExecutor() { if (checkpointExecutor != null && !checkpointExecutor.isShutdown()) { log.debug("Checkpoint executor is running"); return; } String name = getName() + "-pipe-checkpoint-executor"; checkpointExecutor = Executors.newSingleThreadExecutor(new ThreadFactoryBuilder().setNameFormat(name).build()); checkpointExecutor.execute( () -> { try { Thread.sleep(EXECUTOR_DELAY_SECONDS * 1000); } catch (InterruptedException ex) { log.info("{} is interrupted.", name); } while (!checkpointExecutor.isShutdown()) { try { checkpoint(); } catch (Exception ex) { log.error("Failed to checkpoint pipe " + getName(), ex); } try { Thread.sleep(CHECKPOINT_PERIOD_SECONDS * 1000); } catch (InterruptedException ex) { log.info("{} is interrupted.", name); } } }); } /** Stops event streaming for the pipe. */ public void stop() { if (keepAliveExecutor != null) { keepAliveExecutor.shutdownNow(); } if (checkpointExecutor != null) { checkpointExecutor.shutdownNow(); } if (errorHandlingExecutor != null) { errorHandlingExecutor.shutdownNow(); } source.clear(); destination.clear(); close(); source.removeListener(sourceListener); destination.removeListener(destinationListener); metrics.stop(); } /** Opens the {@link Source} and {@link Destination} to initiate event streaming */ private synchronized void open() { destination.open(); source.open(); metrics.open(); } /** * Closes the {@link Source} and {@link Destination} to terminate event streaming, and checkpoints * the last recorded {@link Source} state. */ private synchronized void close() { if (source.isStarted()) { source.close(); } if (destination.isStarted()) { destination.close(); } checkpoint(); metrics.close(); } public void removeSourceListener() { source.removeListener(sourceListener); } /** @return whether the pipe is currently streaming events */ public boolean isStarted() { return source.isStarted() && destination.isStarted(); } /** Checkpoints the source according to the last streamed {@link Mutation} in the pipe */ public void checkpoint() { source.checkpoint(getLastMutation()); } final class SourceListener extends Source.Listener { public void onMutation(List<? extends Mutation<?>> mutations) { destination.send(mutations); } public void onError(Throwable error) { errorHandlingExecutor.execute(Pipe.this::close); } } final class DestinationListener extends Destination.Listener { public void onError(Exception ex) { errorHandlingExecutor.execute(Pipe.this::close); } } }
2,033
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/pipe/PipeManager.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.pipe; import com.google.common.collect.Maps; import com.google.common.collect.Table; import com.google.common.collect.Tables; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; /** * Responsible for managing a collection of {@link Pipe}s for a set of resources. * * <p>A resource is typically associated with a data source, ex: a MySQL database */ @Slf4j @NoArgsConstructor public class PipeManager { private static final long CHECK_STOPPED_WAIT_MILLISEC = 1000L; private static final int CHECK_STOPPED_WAIT_TIMEOUT_SECONDS = 30; /** * Mapped table of [Resource][Partition][Pipes]. In other words, registered resource will have a * set of partitions, each of which will have a collection of {@link Pipe}s registered. */ private final Table<String, String, List<Pipe>> pipeTable = Tables.newCustomTable(Maps.newConcurrentMap(), Maps::newConcurrentMap); private final Executor executor = Executors.newSingleThreadExecutor(); /** * Registers a pipe for the given resource. * * @param name the resource name * @param pipe the pipe */ public void addPipe(@NonNull final String name, @NonNull final Pipe pipe) { addPipe(name, getDefaultPartition(name), pipe); } /** * Registers a {@link Pipe} for the given resource partition * * @param name The resource name * @param partition the partition name * @param pipe the {@link Pipe} */ public void addPipe( @NonNull final String name, @NonNull final String partition, @NonNull final Pipe pipe) { addPipes(name, partition, Collections.singletonList(pipe)); } /** * Registers a list of {@link Pipe}s for the give resource partition * * @param name The resource name * @param partition the partition name * @param pipes the list of {@link Pipe}s */ public void addPipes( @NonNull final String name, @NonNull final String partition, @NonNull final List<Pipe> pipes) { log.debug("Adding pipes for {} / {}", name, partition); pipes.forEach(Pipe::start); pipeTable.put(name, partition, pipes); log.info("Added pipes for {} / {}", name, partition); } private static String getDefaultPartition(final String name) { return String.format("%s_%d", name, 0); } /** @return whether the given resource is registered. */ public boolean contains(@NonNull final String name) { return pipeTable.containsRow(name); } /** @return whether the given resource partition is registered. */ public boolean contains(@NonNull final String name, @NonNull final String partition) { return pipeTable.contains(name, partition); } public boolean isEmpty() { return pipeTable.isEmpty(); } /** @return all partitions for a given registered resource. */ public Set<String> getPartitions(@NonNull final String name) { return pipeTable.row(name).keySet(); } /** * Removes a resource partition. * * @param name the resource * @param partition the partition */ public void removePipe(@NonNull final String name, @NonNull final String partition) { log.debug("Removing pipes for {} / {}", name, partition); final List<Pipe> pipes = pipeTable.get(name, partition); if (pipes == null || pipes.isEmpty()) { log.info("Pipes do not exist for {} / {}", name, partition); return; } pipeTable.remove(name, partition); pipes.forEach( pipe -> { // Remove source listener here to avoid deadlock, as this may be run in a different thread // from source-processor thread pipe.removeSourceListener(); pipe.stop(); }); log.info("Removed pipes for {} / {}", name, partition); } public void executeAsync(@NonNull final Runnable operation) { executor.execute(operation); } /** Starts all {@link Pipe}s for all managed resources. */ public void start() throws Exception { log.debug("Starting pipe manager"); pipeTable .values() .parallelStream() .flatMap(Collection::parallelStream) .forEach( pipe -> { try { pipe.start(); } catch (Exception ex) { log.error("Failed to start pipe " + pipe.getName(), ex); } }); log.info("Started pipe manager"); } /** Starts all {@link Pipe}s for all managed resources. */ public void stop() { log.debug("Stopping pipe manager"); pipeTable .values() .parallelStream() .flatMap(Collection::parallelStream) .forEach( pipe -> { try { pipe.stop(); } catch (Exception ex) { log.error("Failed to stop pipe " + pipe.getName(), ex); } }); log.info("Stopped pipe manager"); } public boolean allPipesStopped() { return pipeTable .values() .parallelStream() .flatMap(Collection::parallelStream) .noneMatch(Pipe::isStarted); } public void waitUntilStopped() throws Exception { int periods = 0; while (!allPipesStopped()) { if (CHECK_STOPPED_WAIT_MILLISEC * periods++ >= 1000 * CHECK_STOPPED_WAIT_TIMEOUT_SECONDS) { throw new TimeoutException( String.format( "Not all pipes were stopped completely within %s seconds", CHECK_STOPPED_WAIT_TIMEOUT_SECONDS)); } Thread.sleep(CHECK_STOPPED_WAIT_MILLISEC); } } }
2,034
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/validator/MutationOrderValidator.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.validator; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.Validator; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Responsible for validating that {@link Mutation}s are streamed in order. This is typically used * as a {@link com.airbnb.spinaltap.common.source.Source.Listener} or {@link * com.airbnb.spinaltap.common.destination.Destination.Listener} to enforce {@link Mutation} * ordering guarantee in run-time. */ @Slf4j @RequiredArgsConstructor public final class MutationOrderValidator implements Validator<Mutation<?>> { /** The handler to execute on out-of-order {@link Mutation}. */ @NonNull private final Consumer<Mutation<?>> handler; /** The id of the last {@link Mutation} validated so far. */ private AtomicLong lastSeenId = new AtomicLong(-1); /** * Validates a {@link Mutation} is received in order, otherwise triggers the specified handler. */ @Override public void validate(@NonNull final Mutation<?> mutation) { final long mutationId = mutation.getMetadata().getId(); log.debug("Validating order for mutation with id {}.", mutationId); if (lastSeenId.get() > mutationId) { log.warn( "Mutation with id {} is out of order and should precede {}.", mutationId, lastSeenId); handler.accept(mutation); } lastSeenId.set(mutationId); } /** Resets the state of the {@link Validator}. */ @Override public void reset() { lastSeenId.set(-1); } }
2,035
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/Joiner.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import javax.annotation.Nullable; /** * Joins two objects to produce a third. * * @param <S> The first object type. * @param <T> The second object type. * @param <R> The result object type. */ @FunctionalInterface public interface Joiner<S, T, R> { /** * Applies the joiner on a pair of objects * * @param first the first object to join * @param second the second object to join * @return the resulting joined object */ @Nullable R apply(@Nullable S first, @Nullable T second); }
2,036
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/JsonUtil.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.joda.JodaModule; import lombok.experimental.UtilityClass; /** Utility class for json operations and components. */ @UtilityClass public class JsonUtil { /** The {@link ObjectMapper} used for json SerDe. */ public ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static { OBJECT_MAPPER.registerModule(new JodaModule()); } }
2,037
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ClassBasedMapper.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import com.google.common.base.Preconditions; import java.util.HashMap; import java.util.Map; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; /** Maps an object according to the registered mapper by {@link Class} type. */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public class ClassBasedMapper<T, R> implements Mapper<T, R> { @NonNull private final Map<Class<? extends T>, Mapper<T, ? extends R>> locator; public static <T, R> ClassBasedMapper.Builder<T, R> builder() { return new ClassBasedMapper.Builder<>(); } @Override public R map(@NonNull final T object) { Mapper<T, ? extends R> mapper = locator.get(object.getClass()); Preconditions.checkState(mapper != null, "No mapper found for type " + object.getClass()); return mapper.map(object); } @NoArgsConstructor(access = AccessLevel.PRIVATE) public static class Builder<T, R> { private final Map<Class<? extends T>, Mapper<? extends T, ? extends R>> locator = new HashMap<>(); public <S extends T> Builder<T, R> addMapper(Class<S> klass, Mapper<S, ? extends R> mapper) { locator.put(klass, mapper); return this; } @SuppressWarnings({"unchecked", "rawtypes"}) public Mapper<T, R> build() { return new ClassBasedMapper(locator); } } }
2,038
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ZookeeperRepository.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import com.fasterxml.jackson.core.type.TypeReference; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.curator.framework.CuratorFramework; /** * {@link Repository} implement with Zookeeper as backing store for objects. * * @param <T> the object type. */ @RequiredArgsConstructor public class ZookeeperRepository<T> implements Repository<T> { @NonNull private final CuratorFramework zkClient; @NonNull private final String path; @NonNull private final TypeReference<? extends T> propertyClass; @Override public boolean exists() throws Exception { return zkClient.checkExists().forPath(path) != null; } @Override public void create(T data) throws Exception { zkClient .create() .creatingParentsIfNeeded() .forPath(path, JsonUtil.OBJECT_MAPPER.writeValueAsBytes(data)); } @Override public void set(T data) throws Exception { zkClient.setData().forPath(path, JsonUtil.OBJECT_MAPPER.writeValueAsBytes(data)); } @Override public void update(T data, DataUpdater<T> updater) throws Exception { if (exists()) { set(updater.apply(get(), data)); } else { create(data); } } @Override public T get() throws Exception { byte[] value = zkClient.getData().forPath(path); return JsonUtil.OBJECT_MAPPER.readValue(value, propertyClass); } @Override public void remove() throws Exception { if (exists()) { zkClient.delete().guaranteed().forPath(path); } } }
2,039
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/Mapper.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; /** * Responsible for mapping between objects. * * @param <T> The mapped from object type. * @param <R> The mapped to object type. */ @FunctionalInterface public interface Mapper<T, R> { /** * Maps an object to another. * * @param object the object to map. * @return the resulting mapped object. */ R map(T object); }
2,040
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/StateRepositoryFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import com.airbnb.spinaltap.common.source.MysqlSourceState; import com.airbnb.spinaltap.common.source.SourceState; import java.util.Collection; /** Factory for {@link Repository}s that store {@link SourceState} objects. */ public interface StateRepositoryFactory<S extends SourceState> { /** * @return the {@link Repository} of the {@link MysqlSourceState} object for a given resource and * partition. */ Repository<S> getStateRepository(String resourceName, String partitionName); /** * @return the {@link Repository} of the history of {@link SourceState} objects for a given * resource and partition. */ Repository<Collection<S>> getStateHistoryRepository(String resourceName, String partitionName); }
2,041
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ConcurrencyUtil.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; import javax.validation.constraints.Min; import lombok.NonNull; import lombok.experimental.UtilityClass; /** Utility methods for concurrency operations */ @UtilityClass public class ConcurrencyUtil { /** * Attempts to shutdown the {@link ExecutorService}. If the service does not terminate within the * specified timeout, a force shutdown will be triggered. * * @param executorService the {@link ExecutorService}. * @param timeout the timeout. * @param unit the time unit. * @return {@code true} if shutdown was successful within the specified timeout, {@code false} * otherwise. */ public boolean shutdownGracefully( @NonNull ExecutorService executorService, @Min(1) long timeout, @NonNull TimeUnit unit) { boolean shutdown = false; executorService.shutdown(); try { shutdown = executorService.awaitTermination(timeout, unit); } catch (InterruptedException e) { executorService.shutdownNow(); } if (!shutdown) { executorService.shutdownNow(); } return shutdown; } }
2,042
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/Validator.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; /** * Responsible for validation logic on an object. * * @param <T> The object type. */ public interface Validator<T> { /** * Validates the object. * * @param object the object */ void validate(T object); /** Resets the state of the validator */ void reset(); }
2,043
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/BatchMapper.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import java.util.List; /** * Responsible for mapping a list of objects. * * @param <T> The mapped from object type. * @param <R> The mapped to object type. */ @FunctionalInterface public interface BatchMapper<T, R> { /** * Applies the mapping function on the list of objects. * * @param objects the objects to map. * @return the mapped objects. */ List<R> apply(List<T> objects); }
2,044
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/Repository.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; /** * Represents a single object data store repository. * * @param <T> the object type stored in the repository. */ public interface Repository<T> { /** @return whether an object exists */ boolean exists() throws Exception; /** * Creates a new object. * * @param value the object value. */ void create(T value) throws Exception; /** * Sets the current object value. * * @param value the object value. */ void set(T value) throws Exception; /** * Updates the current object value given a {@link DataUpdater}. * * @param value the object value. * @param updater the updater . */ void update(T value, DataUpdater<T> updater) throws Exception; /** Retrieves the current object value. */ T get() throws Exception; /** Delete the current object */ void remove() throws Exception; /** * Responsible for determining the object value, as a function of the current value and new value. * * @param <T> the object value type. */ interface DataUpdater<T> { T apply(T currentValue, T newValue); } }
2,045
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/KeyProvider.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; /** * Responsible for providing a key for an object. * * @param <T> The object type. * @param <T> The key type. */ @FunctionalInterface public interface KeyProvider<T, R> { /** * Gets the key for an object. * * @param object the object to get the key for. * @return the resulting key. */ R get(T object); }
2,046
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ErrorHandler.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import com.airbnb.spinaltap.common.exception.SpinaltapException; /** Responsible for handling {@code SpinaltapException}s. */ @FunctionalInterface public interface ErrorHandler { void handle(SpinaltapException e) throws SpinaltapException; }
2,047
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ChainedFilter.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import java.util.ArrayList; import java.util.List; import lombok.AccessLevel; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; /** * Represents a chain of {@link Filter}s, where all {@link Filter} conditions need to pass. * * @param <T> the filtered object type. */ @RequiredArgsConstructor public class ChainedFilter<T> implements Filter<T> { @NonNull private final List<Filter<T>> filters; public static <T> Builder<T> builder() { return new Builder<>(); } /** * Applies the filters on the object. * * @param object the object to filter. * @return {@code true} if all filter conditions pass, {@code false} otherwise. */ public boolean apply(final T object) { return filters.stream().allMatch(filter -> filter.apply(object)); } @NoArgsConstructor(access = AccessLevel.PRIVATE) public static final class Builder<T> { private final List<Filter<T>> filters = new ArrayList<>(); public Builder<T> addFilter(Filter<T> filter) { filters.add(filter); return this; } public Filter<T> build() { return new ChainedFilter<>(filters); } } }
2,048
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/ThreeWayJoiner.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; import javax.annotation.Nullable; /** * Joins three objects to produce a fourth. * * @param <X> The first object type. * @param <Y> The second object type. * @param <Z> The third object type. * @param <R> The result object type. */ @FunctionalInterface public interface ThreeWayJoiner<X, Y, Z, R> { /** * Applies the joiner on a triplet of objects. * * @param first the first object to join. * @param second the second object to join. * @param third the third object to join. * @return the resulting joined object. */ @Nullable R apply(@Nullable X first, @Nullable Y second, @Nullable Z third); }
2,049
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/util/Filter.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.util; /** * Responsible for filtering object * * @param <T> The filtered object type */ @FunctionalInterface public interface Filter<T> { /** * Applies the filter on the object * * @param object the object to filter * @return {@code true} if the filter condition passes, {@code false} otherwise */ boolean apply(T object); }
2,050
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/config/DestinationConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.config; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; import javax.validation.constraints.Min; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; /** Represents a {@link com.airbnb.spinaltap.common.destination.Destination} configuration. */ @Data @NoArgsConstructor public class DestinationConfiguration { public static final String DEFAULT_TYPE = "kafka"; public static final int DEFAULT_BUFFER_SIZE = 0; public static final int DEFAULT_POOL_SIZE = 0; /** The destination type. Default to "kafka". */ @JsonProperty("type") @NonNull private String type = DEFAULT_TYPE; /** * The buffer size. If greater than 0, a {@link * com.airbnb.spinaltap.common.destination.BufferedDestination} will be constructed. */ @Min(0) @JsonProperty("buffer_size") private int bufferSize = DEFAULT_BUFFER_SIZE; /** * The pool size. If greater than 0, a {@link * com.airbnb.spinaltap.common.destination.DestinationPool} will be constructed with the specified * number of {@link com.airbnb.spinaltap.common.destination.Destination}s. */ @Min(0) @JsonProperty("pool_size") private int poolSize = DEFAULT_POOL_SIZE; @JsonProperty("producer_config") private Map<String, Object> producerConfig; }
2,051
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/config/SourceConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.config; import com.fasterxml.jackson.annotation.JsonProperty; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; /** Represents a {@code Source} configuration. */ @Data @NoArgsConstructor @AllArgsConstructor public class SourceConfiguration { private static int DEFAULT_REPLICAS = 3; private static int DEFAULT_PARTITIONS = 1; public SourceConfiguration( @NonNull final String name, final String type, final String instanceTag, @NonNull final DestinationConfiguration destinationConfiguration) { this.name = name; this.type = type; this.instanceGroupTag = instanceTag; this.destinationConfiguration = destinationConfiguration; } public SourceConfiguration(String type, String instanceTag) { this.type = type; this.instanceGroupTag = instanceTag; } /** The source name. */ @NotNull @JsonProperty private String name; /** * The number of replicas to stream from the source. * * <p>Note: This is only applicable if a cluster solution is employed. A Master-Replica state * transition model is recommended, where one cluster instance (master) is streaming events from a * given source at any point in time. This is required to ensure ordering guarantees. Replicas * will be promoted to Master in case of failure. Increasing number of replicas can be used to * improve fault tolerance. */ @Min(1) @JsonProperty private int replicas = DEFAULT_REPLICAS; /** * The number of stream partitions for a given source. * * <p>Note: This is only applicable if a cluster solution is employed. */ @Min(1) @JsonProperty private int partitions = DEFAULT_PARTITIONS; /** The source type (ex: MySQL, DynamoDB) */ @JsonProperty("type") private String type; /** * The group tag for cluster instances of the given source. * * <p>Note: This is only applicable if a cluster solution is employed. Tagging is used to indicate * the instances streaming a particular source. */ @JsonProperty("instance_group_tag") private String instanceGroupTag; /** The destination configuration for the specified source. */ @JsonProperty("destination") private DestinationConfiguration destinationConfiguration = new DestinationConfiguration(); }
2,052
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/config/TlsConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.config; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.io.FileInputStream; import java.security.KeyStore; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class TlsConfiguration { @JsonProperty("key_store_file_path") private String keyStoreFilePath; @JsonProperty("key_store_password") private String keyStorePassword; @JsonProperty("key_store_type") private String keyStoreType; @JsonProperty("trust_store_file_path") private String trustStoreFilePath; @JsonProperty("trust_store_password") private String trustStorePassword; @JsonProperty("trust_store_type") private String trustStoreType; public KeyManagerFactory getKeyManagerFactory() throws Exception { if (keyStoreFilePath != null && keyStorePassword != null) { KeyStore keyStore = KeyStore.getInstance(keyStoreType == null ? KeyStore.getDefaultType() : keyStoreType); keyStore.load(new FileInputStream(keyStoreFilePath), keyStorePassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); return keyManagerFactory; } return null; } public KeyManager[] getKeyManagers() throws Exception { KeyManagerFactory keyManagerFactory = getKeyManagerFactory(); return keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(); } public TrustManagerFactory getTrustManagerFactory() throws Exception { if (trustStoreFilePath != null && trustStorePassword != null) { KeyStore keyStore = KeyStore.getInstance(trustStoreType == null ? KeyStore.getDefaultType() : trustStoreType); keyStore.load(new FileInputStream(trustStoreFilePath), trustStorePassword.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); return trustManagerFactory; } return null; } public TrustManager[] getTrustManagers() throws Exception { TrustManagerFactory trustManagerFactory = getTrustManagerFactory(); return trustManagerFactory == null ? null : trustManagerFactory.getTrustManagers(); } }
2,053
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/ListenableSource.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.spinaltap.Mutation; import java.util.ArrayList; import java.util.List; import lombok.NonNull; /** * Base {@link Source} implement using <a * href="https://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a> to allow listening to * streamed events and subscribe to lifecycle change notifications. */ abstract class ListenableSource<E extends SourceEvent> implements Source { private final List<Listener> listeners = new ArrayList<>(); @Override public void addListener(@NonNull final Listener listener) { listeners.add(listener); } @Override public void removeListener(@NonNull final Listener listener) { listeners.remove(listener); } protected void notifyMutations(final List<? extends Mutation<?>> mutations) { if (!mutations.isEmpty()) { listeners.forEach(listener -> listener.onMutation(mutations)); } } protected void notifyEvent(E event) { listeners.forEach(listener -> listener.onEvent(event)); } protected void notifyError(Throwable error) { listeners.forEach(listener -> listener.onError(error)); } protected void notifyStart() { listeners.forEach(Source.Listener::onStart); } }
2,054
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/AbstractDataStoreSource.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.ConcurrencyUtil; import com.airbnb.spinaltap.common.util.Filter; import com.airbnb.spinaltap.common.util.Mapper; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import lombok.extern.slf4j.Slf4j; /** * Base implementation for Data Store source (Such as MySQL, DynamoDB). * * @param <E> The event type produced by the source */ @Slf4j public abstract class AbstractDataStoreSource<E extends SourceEvent> extends AbstractSource<E> { private @Nullable ExecutorService processor; public AbstractDataStoreSource( String name, SourceMetrics metrics, Mapper<E, List<? extends Mutation<?>>> mutationMapper, Filter<E> eventFilter) { super(name, metrics, mutationMapper, eventFilter); } @Override protected synchronized void start() { processor = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder().setNameFormat(name + "-source-processor").build()); processor.execute( () -> { try { connect(); } catch (Exception ex) { started.set(false); metrics.startFailure(ex); log.error("Failed to stream events for source " + name, ex); } }); } @Override protected void stop() throws Exception { if (isRunning()) { synchronized (this) { ConcurrencyUtil.shutdownGracefully(processor, 2, TimeUnit.SECONDS); } } disconnect(); } @Override public synchronized boolean isStarted() { return started.get() && isRunning(); } @Override protected synchronized boolean isRunning() { return processor != null && !processor.isShutdown(); } @Override protected synchronized boolean isTerminated() { return processor == null || processor.isTerminated(); } protected abstract void connect() throws Exception; protected abstract void disconnect() throws Exception; protected abstract boolean isConnected(); }
2,055
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/SourceMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.metrics.SpinalTapMetrics; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; /** Responsible for metrics collection for a {@link Source}. */ public class SourceMetrics extends SpinalTapMetrics { protected static final String SOURCE_PREFIX = METRIC_PREFIX + ".source"; private static final String START_METRIC = SOURCE_PREFIX + ".start.count"; private static final String STOP_METRIC = SOURCE_PREFIX + ".stop.count"; private static final String CHECKPOINT_METRIC = SOURCE_PREFIX + ".checkpoint.count"; private static final String START_FAILURE_METRIC = SOURCE_PREFIX + ".start.failure.count"; private static final String STOP_FAILURE_METRIC = SOURCE_PREFIX + ".stop.failure.count"; private static final String CHECKPOINT_FAILURE_METRIC = SOURCE_PREFIX + ".checkpoint.failure.count"; private static final String EVENT_COUNT_METRIC = SOURCE_PREFIX + ".event.count"; private static final String EVENT_FAILURE_METRIC = SOURCE_PREFIX + ".event.failure.count"; private static final String EVENT_LAG_METRIC = SOURCE_PREFIX + ".event.lag"; private static final String EVENT_LAG_GAUGE_METRIC = SOURCE_PREFIX + ".event.lag.gauge"; private static final String EVENT_PROCESS_TIME_METRIC = SOURCE_PREFIX + ".event.process.time"; private static final String EVENT_OUT_OF_ORDER_METRIC = SOURCE_PREFIX + ".event.out_of_order.count"; private static final String MUTATION_OUT_OF_ORDER_METRIC = SOURCE_PREFIX + ".mutation.out_of_order.count"; private final AtomicReference<Long> eventLag = new AtomicReference<>(); public SourceMetrics( String sourceName, String sourceType, TaggedMetricRegistry taggedMetricRegistry) { this(sourceName, sourceType, ImmutableMap.of(), taggedMetricRegistry); } public SourceMetrics( String sourceName, String sourceType, Map<String, String> tags, TaggedMetricRegistry metricRegistry) { super( ImmutableMap.<String, String>builder() .put(SOURCE_TYPE_TAG, sourceType) .put(SOURCE_NAME_TAG, sourceName) .putAll(tags) .build(), metricRegistry); registerGauge(EVENT_LAG_GAUGE_METRIC, eventLag::get); } public void start() { inc(START_METRIC); } public void stop() { inc(STOP_METRIC); } public void checkpoint() { inc(CHECKPOINT_METRIC); } public void startFailure(Throwable error) { incError(START_FAILURE_METRIC, error); } public void stopFailure(Throwable error) { incError(STOP_FAILURE_METRIC, error); } public void checkpointFailure(Throwable error) { incError(CHECKPOINT_FAILURE_METRIC, error); } public void eventFailure(Throwable error) { incError(EVENT_FAILURE_METRIC, error); } public void eventReceived(SourceEvent event) { long lag = System.currentTimeMillis() - event.getTimestamp(); Map<String, String> eventTags = getTags(event); inc(EVENT_COUNT_METRIC, eventTags, event.size()); update(EVENT_LAG_METRIC, lag, eventTags); eventLag.set(lag); } public void processEventTime(SourceEvent sourceEvent, long timeInMilliseconds) { update(EVENT_PROCESS_TIME_METRIC, timeInMilliseconds, getTags(sourceEvent)); } public void outOfOrder(SourceEvent event) { inc(EVENT_OUT_OF_ORDER_METRIC, getTags(event)); } public void outOfOrder(Mutation<?> mutation) { inc(MUTATION_OUT_OF_ORDER_METRIC, getTags(mutation)); } @Override public void clear() { removeGauge(EVENT_LAG_GAUGE_METRIC); eventLag.set(null); } }
2,056
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/SourceEvent.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** Represents a base event streamed from a {@link Source}. */ @Getter @ToString @NoArgsConstructor @AllArgsConstructor public abstract class SourceEvent { private long timestamp = System.currentTimeMillis(); /** Returns the number of entities in the event */ public int size() { return 1; } }
2,057
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/MysqlSourceState.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.spinaltap.mysql.BinlogFilePos; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Represents the state of a {@link Source}, based on the last {@link SourceEvent} streamed. This is * used to mark the checkpoint for the {@link Source}, which will help indicate what position to * point to in the changelog on restart. * * <p>At the moment, the implement is coupled to binlog event state and therefore confined to {@code * MysqlSource} usage. */ @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class MysqlSourceState extends SourceState { /** The timestamp of the last streamed {@link SourceEvent} in the changelog. */ @JsonProperty private long lastTimestamp; /** The offset of the last streamed {@link SourceEvent} in the changelog. */ @JsonProperty private long lastOffset; /** The {@link BinlogFilePos} of the last streamed {@link SourceEvent} in the changelog. */ @JsonProperty private BinlogFilePos lastPosition; public MysqlSourceState( final long lastTimestamp, final long lastOffset, final long currentLeaderEpoch, final BinlogFilePos lastPosition) { super(currentLeaderEpoch); this.lastTimestamp = lastTimestamp; this.lastOffset = lastOffset; this.lastPosition = lastPosition; } }
2,058
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/AbstractSource.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.exception.SourceException; import com.airbnb.spinaltap.common.util.Filter; import com.airbnb.spinaltap.common.util.Mapper; import com.airbnb.spinaltap.common.util.Validator; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Base abstract implementation of {@link Source}. * * @param <E> The {@link SourceEvent} type produced by the given {@link Source}. */ @Slf4j @RequiredArgsConstructor public abstract class AbstractSource<E extends SourceEvent> extends ListenableSource<E> { @NonNull @Getter protected final String name; @NonNull protected final SourceMetrics metrics; @NonNull protected final AtomicBoolean started = new AtomicBoolean(false); /** Maps the {@link Source} event to the corresponding {@link Mutation}. */ private final Mapper<E, List<? extends Mutation<?>>> mutationMapper; /** Filters the {@link SourceEvent}s. */ private final Filter<E> eventFilter; @Override public final void open() { try { if (isStarted()) { log.info("Source {} already started", name); return; } Preconditions.checkState( isTerminated(), "Previous processor thread has not terminated for source %s", name); initialize(); notifyStart(); started.set(true); start(); log.info("Started source {}", name); metrics.start(); } catch (Throwable ex) { final String errorMessage = String.format("Failed to start source %s", name); log.error(errorMessage, ex); metrics.startFailure(ex); close(); throw new SourceException(errorMessage, ex); } } @Override public final void close() { try { stop(); started.set(false); log.info("Stopped source {}", name); metrics.stop(); } catch (Throwable ex) { log.error("Failed to stop source " + name, ex); metrics.stopFailure(ex); } } @Override public final void checkpoint(Mutation<?> mutation) { try { log.info("Checkpoint source {}", name); commitCheckpoint(mutation); metrics.checkpoint(); } catch (Throwable ex) { final String errorMessage = String.format("Failed to checkpoint source %s", name); log.error(errorMessage, ex); metrics.checkpointFailure(ex); throw new SourceException(errorMessage, ex); } } @Override public void clear() { metrics.clear(); } protected abstract void initialize(); protected abstract void start() throws Exception; protected abstract void stop() throws Exception; protected abstract void commitCheckpoint(Mutation<?> mutation); protected abstract boolean isRunning(); protected abstract boolean isTerminated(); /** * Processes an event produced by the {@link Source} and notifies {@link Source.Listener} * subscribers of the corresponding {@link Mutation}s. */ public final void processEvent(final E event) { try { if (!eventFilter.apply(event)) { log.debug("Event filtered from source {}. Skipping. event={}", name, event); return; } notifyEvent(event); final Stopwatch stopwatch = Stopwatch.createStarted(); metrics.eventReceived(event); log.debug("Received event from source {}. event={}", name, event); notifyMutations(mutationMapper.map(event)); stopwatch.stop(); final long time = stopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.processEventTime(event, time); } catch (Exception ex) { if (!isStarted()) { // Do not process the exception if streaming has stopped. return; } final String errorMessage = String.format("Failed to process event from source %s", name); log.error(errorMessage, ex); metrics.eventFailure(ex); notifyError(ex); throw new SourceException(errorMessage, ex); } } public final void addEventValidator(@NonNull final Validator<E> validator) { addListener( new Listener() { @Override public void onStart() { validator.reset(); } @Override @SuppressWarnings("unchecked") public void onEvent(SourceEvent event) { validator.validate((E) event); } }); } public final <M extends Mutation<?>> void addMutationValidator( @NonNull final Validator<M> validator) { addListener( new Listener() { @Override public void onStart() { validator.reset(); } @Override @SuppressWarnings("unchecked") public void onMutation(List<? extends Mutation<?>> mutations) { mutations.forEach(mutation -> validator.validate((M) mutation)); } }); } }
2,059
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/Source.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.destination.Destination; import java.util.List; /** * Represents the originating end of the {@link com.airbnb.spinaltap.common.pipe.Pipe}, where {@link * SourceEvent}s are received and transformed to {@link Mutation}s. */ public interface Source { /** The name of the source */ String getName(); /** Adds a {@link Listener} to the source. */ void addListener(Listener listener); /** Removes a {@link Listener} from the source. */ void removeListener(Listener listener); /** Whether the source is started and processing events. */ boolean isStarted(); /** * Initializes the source and prepares for event processing. * * <p>The operation should be idempotent. */ void open(); /** * Stops event processing and closes the source. * * <p>The operation should be idempotent. */ void close(); /** * Clears the state of the source. * * <p>The operation should be idempotent. */ void clear(); /** * Commits the source checkpoint on the specified {@link Mutation}. On source start, streaming * will begin from the last marked checkpoint. */ void checkpoint(Mutation<?> mutation); /** Represents a source listener to get notified of events and lifecycle changes. */ abstract class Listener { /** Action to perform after the {@link Destination} has started. */ public void onStart() {} /** Action to perform after a {@link SourceEvent}s has been received. */ public void onEvent(SourceEvent event) {} /** Action to perform after a {@link Mutation}s has been detected. */ public void onMutation(List<? extends Mutation<?>> mutations) {} /** Action to perform when an error is caught on processing an event. */ public void onError(Throwable error) {} } }
2,060
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/source/SourceState.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.source; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public abstract class SourceState { /** * The leader epoch for the {@code Source}. The epoch acts as a high watermark, and is typically * incremented on leader election. * * <p>Note: This is only applicable if a cluster solution is employed. It is is used to mitigate * network partition (split brain) scenarios, and avoid having two cluster nodes concurrently * streaming from the same {@link Source}. */ @JsonProperty private long currentLeaderEpoch; }
2,061
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/DestinationMetrics.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.metrics.SpinalTapMetrics; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; /** Responsible for metrics collection for a {@link Destination}. */ public class DestinationMetrics extends SpinalTapMetrics { private static final String DESTINATION_PREFIX = METRIC_PREFIX + ".destination"; private static final String START_METRIC = DESTINATION_PREFIX + ".start.count"; private static final String START_FAILURE_METRIC = DESTINATION_PREFIX + ".start.failure.count"; private static final String PUBLISH_METRIC = DESTINATION_PREFIX + ".publish.success.count"; private static final String PUBLISH_FAILURE_METRIC = DESTINATION_PREFIX + ".publish.failure.count"; private static final String PUBLISH_BATCH_SIZE_METRIC = DESTINATION_PREFIX + ".publish.batch.size"; private static final String PUBLISH_LAG_METRIC = DESTINATION_PREFIX + ".publish.lag"; private static final String PUBLISH_LAG_GAUGE_METRIC = DESTINATION_PREFIX + ".publish.lag.gauge"; private static final String PUBLISH_TIME_METRIC = DESTINATION_PREFIX + ".publish.time"; private static final String PUBLISH_OUT_OF_ORDER_METRIC = DESTINATION_PREFIX + ".publish.out.of.order.count"; private static final String IGNORE_RECORD_TOO_LARGE_METRIC = DESTINATION_PREFIX + ".publish.record.too.large.count"; private static final String SEND_TIME_METRIC = DESTINATION_PREFIX + ".send.time"; private static final String SEND_FAILURE_METRIC = DESTINATION_PREFIX + ".send.failure.count"; private static final String BUFFER_SIZE_METRIC = DESTINATION_PREFIX + ".buffer.size"; private static final String BUFFER_FULL_METRIC = DESTINATION_PREFIX + ".buffer.full"; private static final String OUT_OF_ORDER_METRIC = DESTINATION_PREFIX + ".mutation.out_of_order.count"; private final AtomicReference<Long> mutationLag = new AtomicReference<>(); public DestinationMetrics( String sourceName, String sourceType, TaggedMetricRegistry metricRegistry) { this(sourceName, sourceType, ImmutableMap.of(), metricRegistry); } public DestinationMetrics( String sourceName, String sourceType, Map<String, String> tags, TaggedMetricRegistry metricRegistry) { this( ImmutableMap.<String, String>builder() .put(SOURCE_NAME_TAG, sourceName) .put(SOURCE_TYPE_TAG, sourceType) .putAll(tags) .build(), metricRegistry); } public DestinationMetrics( ImmutableMap<String, String> tags, TaggedMetricRegistry metricRegistry) { super(tags, metricRegistry); registerGauge(PUBLISH_LAG_GAUGE_METRIC, mutationLag::get); } public void start() { inc(START_METRIC); } public void startFailure(Throwable error) { incError(START_FAILURE_METRIC, error); } public void publishSucceeded(List<? extends Mutation<?>> mutations) { long lastTimestamp = mutations .stream() .map(mutation -> mutation.getMetadata().getTimestamp()) .max(Long::compare) .orElse(0L); mutationLag.set(System.currentTimeMillis() - lastTimestamp); update(PUBLISH_BATCH_SIZE_METRIC, mutations.size()); mutations.forEach( mutation -> { long lag = System.currentTimeMillis() - mutation.getMetadata().getTimestamp(); Map<String, String> mutationTags = getTags(mutation); update(PUBLISH_LAG_METRIC, lag, mutationTags); inc(PUBLISH_METRIC, mutationTags); }); } public void publishFailed(Mutation<?> mutation, Throwable error) { incError(PUBLISH_FAILURE_METRIC, error, getTags(mutation)); } public void publishOutOfOrder(String tpName) { Map<String, String> topicTags = Maps.newHashMap(); topicTags.put(TOPIC_NAME_TAG, tpName); inc(PUBLISH_OUT_OF_ORDER_METRIC, topicTags); } public void publishRecordTooLarge(String tpName) { Map<String, String> topicTags = Maps.newHashMap(); topicTags.put(TOPIC_NAME_TAG, tpName); inc(IGNORE_RECORD_TOO_LARGE_METRIC, topicTags); } public void publishTime(long timeInMilliseconds) { update(PUBLISH_TIME_METRIC, timeInMilliseconds); } public void sendFailed(Throwable error) { incError(SEND_FAILURE_METRIC, error); } public void sendTime(long delayInMilliseconds) { update(SEND_TIME_METRIC, delayInMilliseconds); } public void bufferSize(int size, Mutation.Metadata metadata) { update(BUFFER_SIZE_METRIC, size, getTags(metadata)); } public void bufferFull(Mutation.Metadata metadata) { inc(BUFFER_FULL_METRIC, getTags(metadata)); } public void outOfOrder(Mutation<?> mutation) { inc(OUT_OF_ORDER_METRIC, getTags(mutation)); } @Override public void clear() { removeGauge(PUBLISH_LAG_GAUGE_METRIC); mutationLag.set(null); } }
2,062
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/BufferedDestination.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.exception.DestinationException; import com.airbnb.spinaltap.common.util.ConcurrencyUtil; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import javax.validation.constraints.Min; import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Represents a {@link Destination} implement with a bounded in-memory buffer. This is used to solve * the Producer-Consumer problem between {@link com.airbnb.spinaltap.common.source.Source} and * {@link Destination} processing, resulting in higher concurrency and reducing overall event * latency. */ @Slf4j @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class BufferedDestination extends ListenableDestination { @NonNull private final String name; @NonNull private final Destination destination; @NonNull private final DestinationMetrics metrics; @NonNull private final BlockingQueue<List<? extends Mutation<?>>> mutationBuffer; private ExecutorService consumer; public BufferedDestination( @NonNull final String name, @Min(1) final int bufferSize, @NonNull final Destination destination, @NonNull final DestinationMetrics metrics) { this(name, destination, metrics, new ArrayBlockingQueue<>(bufferSize, true)); destination.addListener( new Listener() { public void onError(Exception ex) { notifyError(ex); } }); } public int getRemainingCapacity() { return mutationBuffer.remainingCapacity(); } /** * Adds a list of {@link Mutation}s to the buffer, to be sent to the underlying {@link * Destination}. This action is blocking, i.e. thread will wait if the buffer is full. * * @param mutations the mutations to send */ @Override public void send(@NonNull final List<? extends Mutation<?>> mutations) { try { if (mutations.isEmpty()) { return; } final Stopwatch stopwatch = Stopwatch.createStarted(); final Mutation.Metadata metadata = mutations.get(0).getMetadata(); if (mutationBuffer.remainingCapacity() == 0) { metrics.bufferFull(metadata); } mutationBuffer.put(mutations); metrics.bufferSize(mutationBuffer.size(), metadata); stopwatch.stop(); final long time = stopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.sendTime(time); } catch (Exception ex) { log.error("Failed to send mutations.", ex); metrics.sendFailed(ex); throw new DestinationException("Failed to send mutations", ex); } } /** @return the last published {@link Mutation} to the underlying {@link Destination}. */ public Mutation<?> getLastPublishedMutation() { return destination.getLastPublishedMutation(); } /** * Process all {@link Mutation}s in the buffer, and sends them to the underlying {@link * Destination}. */ void processMutations() throws Exception { final List<List<? extends Mutation<?>>> mutationBatches = new ArrayList<>(); // Execute "take" first to block if there are no mutations present (avoid a busy wait) mutationBatches.add(mutationBuffer.take()); mutationBuffer.drainTo(mutationBatches); destination.send(mutationBatches.stream().flatMap(List::stream).collect(Collectors.toList())); } private void execute() { try { while (isRunning()) { processMutations(); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); log.info("Thread interrupted"); } catch (Exception ex) { metrics.sendFailed(ex); log.info("Failed to send mutation", ex); notifyError(ex); } log.info("Destination stopped processing mutations"); } public synchronized boolean isRunning() { return consumer != null && !consumer.isShutdown(); } public synchronized boolean isTerminated() { return consumer == null || consumer.isTerminated(); } @Override public synchronized boolean isStarted() { return destination.isStarted() && isRunning(); } @Override public void open() { if (isStarted()) { log.info("Destination is already started."); return; } try { Preconditions.checkState(isTerminated(), "Previous consumer thread has not terminated."); mutationBuffer.clear(); destination.open(); synchronized (this) { consumer = Executors.newSingleThreadExecutor( new ThreadFactoryBuilder() .setNameFormat(name + "buffered-destination-consumer") .build()); consumer.execute(this::execute); } log.info("Started destination."); } catch (Exception ex) { log.error("Failed to start destination.", ex); metrics.startFailure(ex); close(); throw new DestinationException("Failed to start destination", ex); } } @Override public void close() { if (!isTerminated()) { ConcurrencyUtil.shutdownGracefully(consumer, 2, TimeUnit.SECONDS); } destination.close(); mutationBuffer.clear(); } public void clear() { destination.clear(); metrics.clear(); } }
2,063
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/Destination.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.spinaltap.Mutation; import java.util.Collections; import java.util.List; /** * Represents the receiving end of the {@link com.airbnb.spinaltap.common.pipe.Pipe}, where {@link * Mutation}s are published, i.e. a Sink. */ public interface Destination { /** @return the last {@link Mutation} that has been successfully published. */ Mutation<?> getLastPublishedMutation(); default void send(Mutation<?> mutation) { send(Collections.singletonList(mutation)); } /** * Publishes a list of {@link Mutation}s. * * <p>Note: On failure, streaming should be halted and the error propagated to avoid potential. * event loss */ void send(List<? extends Mutation<?>> mutations); /** Adds a {@link Listener} to the destination. */ void addListener(Listener listener); /** Removes a {@link Listener} from the destination. */ void removeListener(Listener listener); /** @return whether the destination is started and publishing {@link Mutation}s */ boolean isStarted(); /** * Initializes the destination and prepares for {@link Mutation} publishing. * * <p>The operation should be idempotent. */ void open(); /** * Stops {@link Mutation} publishing and closes the destination. * * <p>The operation should be idempotent. */ void close(); /** * Clears the state of the destination. * * <p>The operation should be idempotent. */ void clear(); /** Represents a destination listener to get notified of events and lifecycle changes. */ abstract class Listener { /** Action to perform after the {@link Destination} has started. */ public void onStart() {} /** Action to perform after a list of {@link Mutation}s has been published. */ public void onSend(List<? extends Mutation<?>> mutations) {} /** Action to perform when an error is caught on send. */ public void onError(Exception ex) {} } }
2,064
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/DestinationBuilder.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.BatchMapper; import com.airbnb.spinaltap.common.util.KeyProvider; import com.airbnb.spinaltap.common.util.Mapper; import com.airbnb.spinaltap.common.util.Validator; import com.airbnb.spinaltap.common.validator.MutationOrderValidator; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; import java.util.function.Supplier; import java.util.stream.Collectors; import javax.validation.constraints.Min; import lombok.NonNull; public abstract class DestinationBuilder<T> { protected BatchMapper<Mutation<?>, T> mapper; protected DestinationMetrics metrics; protected String topicNamePrefix = "spinaltap"; protected boolean largeMessageEnabled = false; protected long delaySendMs = 0; protected Map<String, Object> producerConfig; private String name = ""; private KeyProvider<Mutation<?>, String> keyProvider; private int bufferSize = 0; private int poolSize = 0; private boolean validationEnabled = false; public DestinationBuilder<T> withBatchMapper(@NonNull final BatchMapper<Mutation<?>, T> mapper) { this.mapper = mapper; return this; } public final DestinationBuilder<T> withMapper(@NonNull final Mapper<Mutation<?>, T> mapper) { this.mapper = mutations -> mutations.stream().map(mapper::map).collect(Collectors.toList()); return this; } public final DestinationBuilder<T> withTopicNamePrefix(@NonNull final String topicNamePrefix) { this.topicNamePrefix = topicNamePrefix; return this; } public final DestinationBuilder<T> withMetrics(@NonNull final DestinationMetrics metrics) { this.metrics = metrics; return this; } public final DestinationBuilder<T> withBuffer(@Min(0) final int bufferSize) { this.bufferSize = bufferSize; return this; } public final DestinationBuilder<T> withName(@NonNull final String name) { this.name = name; return this; } public final DestinationBuilder<T> withPool( @Min(0) final int poolSize, @NonNull final KeyProvider<Mutation<?>, String> keyProvider) { this.poolSize = poolSize; this.keyProvider = keyProvider; return this; } public final DestinationBuilder<T> withValidation() { this.validationEnabled = true; return this; } public final DestinationBuilder<T> withProducerConfig(final Map<String, Object> producerConfig) { this.producerConfig = producerConfig; return this; } public final DestinationBuilder<T> withLargeMessage(final boolean largeMessageEnabled) { this.largeMessageEnabled = largeMessageEnabled; return this; } public DestinationBuilder<T> withDelaySendMs(long delaySendMs) { this.delaySendMs = delaySendMs; return this; } public final Destination build() { Preconditions.checkNotNull(mapper, "Mapper was not specified."); Preconditions.checkNotNull(metrics, "Metrics were not specified."); final Supplier<Destination> supplier = () -> { final Destination destination = createDestination(); if (validationEnabled) { registerValidator(destination, new MutationOrderValidator(metrics::outOfOrder)); } if (bufferSize > 0) { return new BufferedDestination(name, bufferSize, destination, metrics); } return destination; }; if (poolSize > 0) { return createDestinationPool(supplier); } return supplier.get(); } protected abstract Destination createDestination(); private Destination createDestinationPool(final Supplier<Destination> supplier) { Preconditions.checkNotNull(keyProvider, "Key provider was not specified"); final List<Destination> destinations = Lists.newArrayList(); for (int i = 0; i < poolSize; i++) { destinations.add(supplier.get()); } return new DestinationPool(keyProvider, destinations); } private void registerValidator(Destination destination, Validator<Mutation<?>> validator) { destination.addListener( new Destination.Listener() { @Override public void onStart() { validator.reset(); } @Override public void onSend(List<? extends Mutation<?>> mutations) { mutations.forEach(validator::validate); } }); } }
2,065
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/ListenableDestination.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.spinaltap.Mutation; import java.util.ArrayList; import java.util.List; import lombok.NonNull; /** * Base {@link Destination} implement using <a * href="https://en.wikipedia.org/wiki/Observer_pattern">observer pattern</a> to allow listening to * streamed events and subscribe to lifecycle change notifications. */ abstract class ListenableDestination implements Destination { private final List<Listener> listeners = new ArrayList<>(); @Override public void addListener(@NonNull final Listener listener) { listeners.add(listener); } @Override public void removeListener(@NonNull final Listener listener) { listeners.remove(listener); } protected void notifyStart() { listeners.forEach(Destination.Listener::onStart); } protected void notifySend(final List<? extends Mutation<?>> mutations) { listeners.forEach(listener -> listener.onSend(mutations)); } protected void notifyError(final Exception ex) { listeners.forEach(listener -> listener.onError(ex)); } @Override public void open() { notifyStart(); } }
2,066
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/DestinationPool.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toList; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.util.KeyProvider; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Represents a pool of {@link Destination}s, where events are routed to the appropriate {@link * Destination} given a partitioning function based on {@link Mutation} key. * * <p>Note: This implement helps to fan-out load, which is particularly useful to keep {@link * Mutation} lag low when there are event spikes. */ @Slf4j @RequiredArgsConstructor(access = AccessLevel.PRIVATE) public final class DestinationPool extends ListenableDestination { @NonNull private final KeyProvider<Mutation<?>, String> keyProvider; @NonNull private final List<Destination> destinations; @NonNull private final boolean[] isActive; private final AtomicBoolean isErrorNotified = new AtomicBoolean(); private Listener destinationListener = new Listener() { public void onError(Exception ex) { // Only notify once if error occurred in multiple destinations if (isErrorNotified.compareAndSet(false, true)) { notifyError(ex); } } }; public DestinationPool( @NonNull final KeyProvider<Mutation<?>, String> keyProvider, @NonNull final List<Destination> destinations) { this(keyProvider, destinations, new boolean[destinations.size()]); destinations.forEach(destination -> destination.addListener(destinationListener)); } public int getPoolSize() { return destinations.size(); } /** * Gets the {@link Mutation} with the earliest id from the last published {@link Mutation}s across * all {@link Destination}s in the pool. * * <p>Note: If there is any {@link Destination} that we have sent {@link Mutation}s to but has not * been published yet, null will be returned as the last published {@link Mutation}. This might * lead to data loss if 1) the {@code Destination} fails to publish, and 2) we checkpoint on * another {@link Destination}'s last published {@link Mutation} that is ahead in position. The * solution is to avoid checkpointing in this scenario by returning null. {@code isActive} is used * in order to disregard {@link Destination}s that have not yet been sent any {@link Mutation}s. */ @Override public synchronized Mutation<?> getLastPublishedMutation() { for (int i = 0; i < destinations.size(); i++) { if (isActive[i] && destinations.get(i).getLastPublishedMutation() == null) { return null; } } return destinations .stream() .map(Destination::getLastPublishedMutation) .filter(Objects::nonNull) .min(Comparator.comparingLong(mutation -> mutation.getMetadata().getId())) .orElse(null); } /** * Partitions the {@link Mutation} list according to the supplied {@link KeyProvider} and routes * to the corresponding {@link Destination}s */ @Override public synchronized void send(@NonNull final List<? extends Mutation<?>> mutations) { mutations .stream() .collect(groupingBy(this::getPartitionId, LinkedHashMap::new, toList())) .forEach( (id, mutationList) -> { log.debug("Sending {} mutations to destination {}.", mutationList.size(), id); // Always retain this order isActive[id] = true; destinations.get(id).send(mutationList); }); } /** The is currently a replication of the logic in {@code kafka.producer.DefaultPartitioner} */ private int getPartitionId(final Mutation<?> mutation) { return Math.abs(keyProvider.get(mutation).hashCode() % destinations.size()); } @Override public boolean isStarted() { return destinations.stream().allMatch(Destination::isStarted); } @Override public void open() { isErrorNotified.set(false); destinations.parallelStream().forEach(Destination::open); } @Override public void close() { destinations.parallelStream().forEach(Destination::close); } @Override public void clear() { destinations.parallelStream().forEach(Destination::clear); } }
2,067
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/destination/AbstractDestination.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.destination; import com.airbnb.spinaltap.Mutation; import com.airbnb.spinaltap.common.exception.DestinationException; import com.airbnb.spinaltap.common.util.BatchMapper; import com.google.common.base.Stopwatch; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @Slf4j @RequiredArgsConstructor public abstract class AbstractDestination<T> extends ListenableDestination { @NonNull private final BatchMapper<Mutation<?>, T> mapper; @NonNull private final DestinationMetrics metrics; private final long delaySendMs; private final AtomicBoolean started = new AtomicBoolean(false); private final AtomicReference<Mutation<?>> lastPublishedMutation = new AtomicReference<>(); @Override public Mutation<?> getLastPublishedMutation() { return lastPublishedMutation.get(); } @SuppressWarnings("unchecked") @Override public void send(@NonNull final List<? extends Mutation<?>> mutations) { if (mutations.isEmpty()) { return; } try { final Stopwatch stopwatch = Stopwatch.createStarted(); final List<T> messages = mapper.apply(mutations.stream().collect(Collectors.toList())); final Mutation<?> latestMutation = mutations.get(mutations.size() - 1); delay(latestMutation); publish(messages); lastPublishedMutation.set(latestMutation); stopwatch.stop(); final long time = stopwatch.elapsed(TimeUnit.MILLISECONDS); metrics.publishTime(time); metrics.publishSucceeded(mutations); log(mutations); notifySend(mutations); } catch (Exception ex) { log.error("Failed to send {} mutations.", mutations.size(), ex); mutations.forEach(mutation -> metrics.publishFailed(mutation, ex)); throw new DestinationException("Failed to send mutations", ex); } } /** * Induces a delay given the configured delay time. * * @param mutation The {@link Mutation} for which to consider the delay * @throws InterruptedException */ private void delay(final Mutation<?> mutation) throws InterruptedException { final long delayMs = System.currentTimeMillis() - mutation.getMetadata().getTimestamp(); if (delayMs >= delaySendMs) { return; } Thread.sleep(delaySendMs - delayMs); } public abstract void publish(List<T> messages) throws Exception; private void log(final List<? extends Mutation<?>> mutations) { mutations.forEach( mutation -> log.trace( "Sent {} mutations with metadata {}.", mutation.getType(), mutation.getMetadata())); } @Override public boolean isStarted() { return started.get(); } @Override public void open() { lastPublishedMutation.set(null); super.open(); started.set(true); } @Override public void close() { started.set(false); } @Override public void clear() { metrics.clear(); } }
2,068
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/EntityDeserializationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; public class EntityDeserializationException extends SpinaltapException { private static final long serialVersionUID = 2604256281318886726L; public EntityDeserializationException(String message, Throwable cause) { super(message, cause); } }
2,069
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/SpinaltapException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; public class SpinaltapException extends RuntimeException { private static final long serialVersionUID = -8074916613284028245L; public SpinaltapException(String message) { super(message); } public SpinaltapException(String message, Throwable cause) { super(message, cause); } }
2,070
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/AttributeValueDeserializationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; /** Exception thrown when a DynamoDB attribute value cannot be deserialized. */ public final class AttributeValueDeserializationException extends EntityDeserializationException { private static final long serialVersionUID = 2442564527939878665L; private static String createMessage(String attributeName, String tableName) { return String.format( "Could not deserialize thrift bytebuffer for DynamoDB attribute %s in table %s.", attributeName, tableName); } public AttributeValueDeserializationException( final String attributeName, final String tableName, final Throwable cause) { super(createMessage(attributeName, tableName), cause); } }
2,071
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/DestinationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; public class DestinationException extends SpinaltapException { private static final long serialVersionUID = -2160287795842968357L; public DestinationException(String message, Throwable cause) { super(message, cause); } }
2,072
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/ColumnDeserializationException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; /** Exception thrown when a MySQL column value cannot be deserialized. */ public final class ColumnDeserializationException extends EntityDeserializationException { private static final long serialVersionUID = 935990977706712032L; private static String createMessage(String columnName, String tableName) { return String.format( "Failed to deserialize MySQL column %s in table %s", columnName, tableName); } public ColumnDeserializationException( final String columnName, final String tableName, final Throwable cause) { super(createMessage(columnName, tableName), cause); } }
2,073
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/spinaltap/common/exception/SourceException.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap.common.exception; public class SourceException extends SpinaltapException { private static final long serialVersionUID = -59599391802331914L; public SourceException(String message, Throwable cause) { super(message, cause); } }
2,074
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/TaggedMetricRegistry.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; import com.codahale.metrics.Metric; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.MetricSet; import java.util.Map; /** * The TaggedMetricRegistry is a proxy for a MetricRegistry that enables tags for Metrics. It relies * on the DatadogReporter to parse metrics of the form metric.name[tag1:value1,tag2:value2] into a * name metric.name and tags tag1:value1 and tag2:value2. * * <p>It proxies the create methods of the MetricRegistry directly. If you want to access the * retrieval methods of the MetricRegistry (such as getCounters()) you should call * getMetricRegistry() to get the underlying registry. * * <p>It uses composition instead of inheritance because Dropwizard statically initializes its * MetricRegistry and makes it difficult to subclass. And composition is fun. */ public class TaggedMetricRegistry { static final String UNTAGGED_SUFFIX = ".untagged"; static final TaggedMetricRegistry NON_INITIALIZED_TAGGED_METRIC_REGISTRY = new TaggedMetricRegistry(); private final MetricRegistry registry; public TaggedMetricRegistry() { this(new MetricRegistry()); } public TaggedMetricRegistry(MetricRegistry registry) { this.registry = registry; } public static String name(String name, String... names) { return MetricRegistry.name(name, names); } public static String name(Class<?> klass, String... names) { return MetricRegistry.name(klass, names); } public <T extends Metric> T register(String name, T metric) { return registry.register(name, metric); } public <T extends Metric> T register(String name, Map<String, String> tags, T metric) { return registry.register(taggedName(name, tags), metric); } public <T extends Metric> T register(String name, T metric, String... tags) { return registry.register(taggedName(name, tags), metric); } public boolean remove(String name) { return registry.remove(name); } public boolean remove(String name, Map<String, String> tags) { return registry.remove(taggedName(name, tags)); } public boolean remove(String name, String... tags) { return registry.remove(taggedName(name, tags)); } /** * Build the tagged metric for Datadog from a map for tags in a key:value format. * * <p>We could validate that the name and tags don't contain [, ] or , because that might cause * problems if it's worth the performance impact. * * @param name the metric name * @param tags the associated tags from a key:value format */ public static String taggedName(String name, Map<String, String> tags) { if (tags == null || tags.isEmpty()) { return name; } return taggedName(name, getTagsAsArray(tags)); } /** * Same as {@link #taggedName(String, Map)}, but takes variable number of tags in simple string * format. */ public static String taggedName(String name, String... tags) { if (tags == null || tags.length < 1) { return name; } final StringBuilder builder = new StringBuilder(); builder.append(name); builder.append("["); boolean first = true; for (String tag : tags) { if (!first) { builder.append(","); } builder.append(tag); first = false; } builder.append("]"); return builder.toString(); } public static String[] getTagsAsArray(Map<String, String> tags) { if (tags == null || tags.isEmpty()) { return null; } // Can use java streams once the language level is upgraded String tagsArray[] = new String[tags.size()]; int index = 0; for (Map.Entry<String, String> entry : tags.entrySet()) { // Allocate the memory initially tagsArray[index++] = new StringBuilder(entry.getKey().length() + 1 + entry.getValue().length()) .append(entry.getKey()) .append(":") .append(entry.getValue()) .toString(); } return tagsArray; } public void registerAll(MetricSet metrics) { registry.registerAll(metrics); } public Counter counter(String name) { return new Counter(registry.counter(name), registry.counter(name + UNTAGGED_SUFFIX)); } public Counter counter(String name, Map<String, String> tags) { return new Counter( registry.counter(taggedName(name, tags)), registry.counter(name + UNTAGGED_SUFFIX)); } public Counter counter(String name, String... tags) { return new Counter( registry.counter(taggedName(name, tags)), registry.counter(name + UNTAGGED_SUFFIX)); } public Histogram histogram(String name) { return new Histogram(registry.histogram(name), registry.histogram(name + UNTAGGED_SUFFIX)); } public Histogram histogram(String name, Map<String, String> tags) { return new Histogram( registry.histogram(taggedName(name, tags)), registry.histogram(name + UNTAGGED_SUFFIX)); } public Histogram histogram(String name, String... tags) { return new Histogram( registry.histogram(taggedName(name, tags)), registry.histogram(name + UNTAGGED_SUFFIX)); } public Meter meter(String name) { return new Meter(registry.meter(name), registry.meter(name + UNTAGGED_SUFFIX)); } public Meter meter(String name, Map<String, String> tags) { return new Meter( registry.meter(taggedName(name, tags)), registry.meter(name + UNTAGGED_SUFFIX)); } public Meter meter(String name, String... tags) { return new Meter( registry.meter(taggedName(name, tags)), registry.meter(name + UNTAGGED_SUFFIX)); } public Timer timer(String name) { return new Timer(registry.timer(name), registry.timer(name + UNTAGGED_SUFFIX)); } public Timer timer(String name, Map<String, String> tags) { return new Timer( registry.timer(taggedName(name, tags)), registry.timer(name + UNTAGGED_SUFFIX)); } public Timer timer(String name, String... tags) { return new Timer( registry.timer(taggedName(name, tags)), registry.timer(name + UNTAGGED_SUFFIX)); } public MetricRegistry getMetricRegistry() { return registry; } }
2,075
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/TaggedMetricRegistryFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; @Slf4j /** * This provides an easy way to get the TaggedMetricRegistry in any class. The initialize must be * called before getting the TaggedMetricRegistry, otherwise the metrics will be lost. * * <p>The TaggedMetricRegistry is also available for injection. Consider injecting it directly in * case you want metrics during object initialization or as a general dependency injection best * practice. */ public class TaggedMetricRegistryFactory { private static volatile TaggedMetricRegistry registry = TaggedMetricRegistry.NON_INITIALIZED_TAGGED_METRIC_REGISTRY; private TaggedMetricRegistryFactory() {} public static void initialize(@NonNull TaggedMetricRegistry taggedMetricRegistry) { registry = taggedMetricRegistry; } public static TaggedMetricRegistry get() { if (registry == TaggedMetricRegistry.NON_INITIALIZED_TAGGED_METRIC_REGISTRY) { log.warn( "get() called before metrics is initialized. return NON_INITIALIZED_TAGGED_METRIC_REGISTRY."); } return registry; } }
2,076
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/Timer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; import com.codahale.metrics.Clock; import java.io.Closeable; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Our own version of the Timer class that multiplexes tagged metrics to tagged and non-tagged * versions, because Datadog is not capable of averaging across tag values correctly. */ public class Timer { private final Clock clock; private final com.codahale.metrics.Timer[] timers; public Timer(Clock clock, com.codahale.metrics.Timer... timers) { this.timers = timers; this.clock = clock; } public Timer(com.codahale.metrics.Timer... timers) { this(Clock.defaultClock(), timers); } /** * Adds a recorded duration. * * @param duration the length of the duration * @param unit the scale unit of {@code duration} */ public void update(long duration, TimeUnit unit) { for (com.codahale.metrics.Timer timer : timers) { timer.update(duration, unit); } } /** * Times and records the duration of event. * * @param event a {@link Callable} whose {@link Callable#call()} method implements a process whose * duration should be timed * @param <T> the type of the value returned by {@code event} * @return the value returned by {@code event} * @throws Exception if {@code event} throws an {@link Exception} */ public <T> T time(Callable<T> event) throws Exception { final long startTime = clock.getTick(); try { return event.call(); } finally { update(clock.getTick() - startTime, TimeUnit.NANOSECONDS); } } /** * Returns a new {@link Context}. * * @return a new {@link Context} * @see Context */ public Context time() { com.codahale.metrics.Timer.Context[] contexts = new com.codahale.metrics.Timer.Context[timers.length]; for (int i = 0; i < timers.length; i++) { contexts[i] = timers[i].time(); } return new Context(contexts); } /** * A timing context. * * @see Timer#time() */ public static class Context implements Closeable { private com.codahale.metrics.Timer.Context[] contexts; private Context(com.codahale.metrics.Timer.Context... contexts) { this.contexts = contexts; } /** * Stops recording the elapsed time, updates the timer and returns the elapsed time in * nanoseconds. */ public long stop() { long elapsed = 0; for (com.codahale.metrics.Timer.Context context : contexts) { elapsed = context.stop(); } return elapsed; } @Override public void close() { stop(); } } }
2,077
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/Counter.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; /** * Our own version of the Counter class that multiplexes tagged metrics to tagged and non-tagged * versions, because Datadog is not capable of averaging across tag values correctly. */ public class Counter { private final com.codahale.metrics.Counter[] counters; public Counter(com.codahale.metrics.Counter... counters) { this.counters = counters; } /** Increment the counter by one. */ public void inc() { inc(1); } /** * Increment the counter by {@code n}. * * @param n the amount by which the counter will be increased */ public void inc(long n) { for (com.codahale.metrics.Counter counter : counters) { counter.inc(n); } } /** Decrement the counter by one. */ public void dec() { dec(1); } /** * Decrement the counter by {@code n}. * * @param n the amount by which the counter will be decreased */ public void dec(long n) { for (com.codahale.metrics.Counter counter : counters) { counter.dec(n); } } }
2,078
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/MetricsTimer.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; import com.google.common.base.Stopwatch; import java.io.Closeable; import java.util.concurrent.TimeUnit; import lombok.Builder; @Builder public class MetricsTimer implements Closeable { private final String metricName; private final TimeUnit timeUnit; private final Stopwatch stopwatch; private final String[] tags; private final TaggedMetricRegistry taggedMetricRegistry; public static class MetricsTimerBuilder { public MetricsTimerBuilder tags(String... tags) { this.tags = tags; return this; } public MetricsTimer build() { if (timeUnit == null) { timeUnit = TimeUnit.MILLISECONDS; } if (stopwatch == null) { stopwatch = Stopwatch.createStarted(); } if (taggedMetricRegistry == null) { taggedMetricRegistry = TaggedMetricRegistryFactory.get(); } return new MetricsTimer(metricName, timeUnit, stopwatch, tags, taggedMetricRegistry); } } @Override public void close() { done(); } public long done() { long requestTime = stopwatch.elapsed(timeUnit); taggedMetricRegistry.histogram(metricName, tags).update(requestTime); return requestTime; } /** * Does not close or record a metric; merely checks the time elapsed since object creation. * * @return the elapsed time in specified time unit */ public long check() { return stopwatch.elapsed(timeUnit); } }
2,079
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/Meter.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; /** * Our own version of the Counter class that multiplexes tagged metrics to tagged and non-tagged * versions, because Datadog is not capable of averaging across tag values correctly. */ public class Meter { private final com.codahale.metrics.Meter[] meters; /** Creates a new {@link Meter}. */ public Meter(com.codahale.metrics.Meter... meters) { this.meters = meters; } /** Mark the occurrence of an event. */ public void mark() { for (com.codahale.metrics.Meter meter : meters) { meter.mark(); } } /** * Mark the occurrence of a given number of events. * * @param n the number of events */ public void mark(long n) { for (com.codahale.metrics.Meter meter : meters) { meter.mark(n); } } }
2,080
0
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common
Create_ds/SpinalTap/spinaltap-common/src/main/java/com/airbnb/common/metrics/Histogram.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.common.metrics; /** * Our own version of the Histogram class that multiplexes tagged metrics to tagged and non-tagged * versions, because Datadog is not capable of averaging across tag values correctly. */ public class Histogram { private final com.codahale.metrics.Histogram[] histograms; public Histogram(com.codahale.metrics.Histogram... histograms) { this.histograms = histograms; } /** * Adds a recorded value. * * @param value the length of the value */ public void update(int value) { update((long) value); } /** * Adds a recorded value. * * @param value the length of the value */ public void update(long value) { for (com.codahale.metrics.Histogram histogram : histograms) { histogram.update(value); } } }
2,081
0
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb/spinaltap/SpinalTapStandaloneConfiguration.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap; import com.airbnb.spinaltap.common.config.TlsConfiguration; import com.airbnb.spinaltap.kafka.KafkaProducerConfiguration; import com.airbnb.spinaltap.mysql.config.MysqlConfiguration; import com.airbnb.spinaltap.mysql.config.MysqlSchemaStoreConfiguration; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import javax.validation.constraints.NotNull; import lombok.Data; /** Represents the {@link SpinalTapStandaloneApp} configuration. */ @Data @JsonIgnoreProperties(ignoreUnknown = true) public class SpinalTapStandaloneConfiguration { public static final int DEFAULT_MYSQL_SERVER_ID = 65535; @NotNull @JsonProperty("zk-connection-string") private String zkConnectionString; @NotNull @JsonProperty("zk-namespace") private String zkNamespace; @NotNull @JsonProperty("kafka-config") private KafkaProducerConfiguration kafkaProducerConfig; /** * Note: The user should have following grants on the source databases: * * <ul> * <li>SELECT * <li>REPLICATION SLAVE * <li>REPLICATION CLIENT * <li>SHOW VIEW * </ul> */ @NotNull @JsonProperty("mysql-user") private String mysqlUser; @NotNull @JsonProperty("mysql-password") private String mysqlPassword; @NotNull @JsonProperty("mysql-server-id") private long mysqlServerId = DEFAULT_MYSQL_SERVER_ID; @JsonProperty("tls-config") private TlsConfiguration tlsConfiguration; @JsonProperty("mysql-schema-store") private MysqlSchemaStoreConfiguration mysqlSchemaStoreConfig; @NotNull @JsonProperty("mysql-sources") private List<MysqlConfiguration> mysqlSources; }
2,082
0
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb/spinaltap/SpinalTapStandaloneApp.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap; import com.airbnb.common.metrics.TaggedMetricRegistry; import com.airbnb.spinaltap.common.pipe.PipeManager; import com.airbnb.spinaltap.kafka.KafkaDestinationBuilder; import com.airbnb.spinaltap.mysql.MysqlPipeFactory; import com.airbnb.spinaltap.mysql.config.MysqlConfiguration; import com.airbnb.spinaltap.mysql.schema.MysqlSchemaManagerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.google.common.collect.ImmutableMap; import java.io.File; import lombok.extern.slf4j.Slf4j; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; /** A standalone single-node application to run SpinalTap process. */ @Slf4j public final class SpinalTapStandaloneApp { public static void main(String[] args) throws Exception { if (args.length != 1) { log.error("Usage: SpinalTapStandaloneApp <config.yaml>"); System.exit(1); } final ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory()); final SpinalTapStandaloneConfiguration config = objectMapper.readValue(new File(args[0]), SpinalTapStandaloneConfiguration.class); final MysqlPipeFactory mysqlPipeFactory = createMysqlPipeFactory(config); final ZookeeperRepositoryFactory zkRepositoryFactory = createZookeeperRepositoryFactory(config); final PipeManager pipeManager = new PipeManager(); for (MysqlConfiguration mysqlSourceConfig : config.getMysqlSources()) { final String sourceName = mysqlSourceConfig.getName(); final String partitionName = String.format("%s_0", sourceName); pipeManager.addPipes( sourceName, partitionName, mysqlPipeFactory.createPipes(mysqlSourceConfig, partitionName, zkRepositoryFactory, 0)); } Runtime.getRuntime().addShutdownHook(new Thread(pipeManager::stop)); } private static MysqlPipeFactory createMysqlPipeFactory( final SpinalTapStandaloneConfiguration config) { return new MysqlPipeFactory( config.getMysqlUser(), config.getMysqlPassword(), config.getMysqlServerId(), config.getTlsConfiguration(), ImmutableMap.of( "kafka", () -> new KafkaDestinationBuilder<>(config.getKafkaProducerConfig())), new MysqlSchemaManagerFactory( config.getMysqlUser(), config.getMysqlPassword(), config.getMysqlSchemaStoreConfig(), config.getTlsConfiguration()), new TaggedMetricRegistry()); } private static ZookeeperRepositoryFactory createZookeeperRepositoryFactory( final SpinalTapStandaloneConfiguration config) { final CuratorFramework zkClient = CuratorFrameworkFactory.builder() .namespace(config.getZkNamespace()) .connectString(config.getZkConnectionString()) .retryPolicy(new ExponentialBackoffRetry(100, 3)) .build(); zkClient.start(); return new ZookeeperRepositoryFactory(zkClient); } }
2,083
0
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb
Create_ds/SpinalTap/spinaltap-standalone/src/main/java/com/airbnb/spinaltap/ZookeeperRepositoryFactory.java
/** * Copyright 2019 Airbnb. Licensed under Apache-2.0. See License in the project root for license * information. */ package com.airbnb.spinaltap; import com.airbnb.spinaltap.common.source.MysqlSourceState; import com.airbnb.spinaltap.common.util.StateRepositoryFactory; import com.airbnb.spinaltap.common.util.ZookeeperRepository; import com.fasterxml.jackson.core.type.TypeReference; import java.util.Collection; import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.apache.curator.framework.CuratorFramework; /** Represents an implement of {@link StateRepositoryFactory} in Zookeeper. */ @RequiredArgsConstructor public final class ZookeeperRepositoryFactory implements StateRepositoryFactory<MysqlSourceState> { @NonNull private final CuratorFramework zkClient; @Override public ZookeeperRepository<MysqlSourceState> getStateRepository( String sourceName, String parition) { return new ZookeeperRepository<>( zkClient, String.format("/spinaltap/pipe/%s/state", sourceName), new TypeReference<MysqlSourceState>() {}); } @Override public ZookeeperRepository<Collection<MysqlSourceState>> getStateHistoryRepository( String sourceName, String partition) { return new ZookeeperRepository<>( zkClient, String.format("/spinaltap/pipe/%s/state_history", sourceName), new TypeReference<Collection<MysqlSourceState>>() {}); } }
2,084
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/ComponentFactoryModuleBuilderTest.java
package com.netflix.fabricator; import java.util.Properties; import javax.annotation.Nullable; import com.netflix.fabricator.properties.PropertiesConfigurationModule; import com.netflix.fabricator.supplier.SupplierWithDefault; import org.junit.Ignore; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.netflix.config.ConfigurationManager; import com.netflix.fabricator.archaius.ArchaiusConfigurationModule; import com.netflix.fabricator.annotations.TypeImplementation; import com.netflix.fabricator.annotations.Type; import com.netflix.fabricator.component.ComponentManager; import com.netflix.fabricator.component.SynchronizedComponentManager; import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException; import com.netflix.fabricator.component.exception.ComponentCreationException; import com.netflix.fabricator.guice.ComponentModuleBuilder; import com.netflix.fabricator.supplier.ListenableSupplier; public class ComponentFactoryModuleBuilderTest { private static final Logger LOG = LoggerFactory.getLogger(ComponentFactoryModuleBuilderTest.class); /** * Example of a subentity * * @author elandau */ public static class SubEntity { public static class Builder { private String str; public Builder withStr(String str) { this.str = str; return this; } public SubEntity build() { return new SubEntity(this); } } private final String str; private SubEntity(Builder init) { this.str = init.str; } public String getString() { return str; } @Override public String toString() { return "SubEntity [str=" + str + "]"; } } /** * Interface for a policy * @author elandau * */ @Type("policy") public static interface Policy { } /** * Implementation of a policy with one String arg * * @author elandau */ @TypeImplementation("pa") public static class PolicyA implements Policy { private final String s; private final Long l; private final Boolean b; private final Double d; private final Integer i; public static class Builder { private String s; private Long l; private Boolean b; private Double d; private Integer i; public Builder withString(String s) { this.s = s; return this; } public Builder withLong(Long l) { this.l = l; return this; } public Builder withInteger(Integer i) { this.i = i; return this; } public Builder withDouble(Double d) { this.d = d; return this; } public Builder withBoolean(Boolean b) { this.b = b; return this; } public PolicyA build() { return new PolicyA(this); } } private PolicyA(Builder init) { this.s = init.s; this.l = init.l; this.b = init.b; this.i = init.i; this.d = init.d; } public String getString() { return this.s; } @Override public String toString() { return "PolicyA [s=" + s + ", l=" + l + ", b=" + b + ", d=" + d + ", i=" + i + "]"; } } /** * A plicy with one string arg and a supplier * @author elandau * */ @TypeImplementation("pb") public static class PolicyB implements Policy { private final Supplier<String> arg1; public static class Builder { private final SupplierWithDefault<String> arg1 = SupplierWithDefault.from("abc"); public Builder withArg1(String arg1) { this.arg1.setValue(arg1); return this; } public Builder withArg1(Supplier<String> arg1) { this.arg1.addOverride(arg1); return this; } public PolicyB build() { return new PolicyB(this); } } private PolicyB(Builder init) { this.arg1 = init.arg1; } @Override public String toString() { return "PolicyB [arg1=" + arg1 + "]"; } } /** * * @author elandau * */ @Type("some") public static abstract class SomeInterface { } public static class SomeInterfaceModule extends AbstractModule { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .manager(SynchronizedComponentManager.class) .build(SomeInterface.class)); } } /** * * @author elandau * */ @TypeImplementation("a") public static class BaseA extends SomeInterface { public static class Builder { private String id; private String prop1; private Policy policy; private final SupplierWithDefault<String> dyn1 = new SupplierWithDefault<String>("dyn1_default"); private final SupplierWithDefault<String> dyn2 = new SupplierWithDefault<String>("dyn2_default"); public Builder withId(String id) { this.id = id; return this; } public Builder withProp1(String prop1) { this.prop1 = prop1; return this; } public Builder withPolicy(Policy policy) { this.policy = policy; return this; } public Builder withDyn1(Supplier<String> supplier) { LOG.info("dyn1=" + supplier.get()); this.dyn1.addOverride(supplier); return this; } public Builder withDyn2(ListenableSupplier<String> supplier) { LOG.info("dyn2=" + supplier.get()); this.dyn2.setSource(supplier); return this; } public BaseA build() { return new BaseA(this); } } private final String id; private final String prop1; private final Policy policy; private final Supplier<String> dyn1; private final ListenableSupplier<String> dyn2; private BaseA(Builder init) { this.id = init.id; this.prop1 = init.prop1; this.policy = init.policy; this.dyn1 = init.dyn1; this.dyn2 = init.dyn2; this.dyn2.onChange(new Function<String, Void>() { public Void apply(@Nullable String input) { LOG.info("Value has changed to : " + input); return null; } }); } @Override public String toString() { return "BaseA [id=" + id + ", prop1=" + prop1 + ", policy=" + policy + ", dyn1=" + dyn1.get() + ", dyn2=" + dyn2.get() + "]"; } } /** * * @author elandau * */ @TypeImplementation("b") public static class BaseB extends SomeInterface { public static class Builder { private String id; public Builder withId(String id) { this.id = id; return this; } public BaseB build() { return new BaseB(this); } } private final String id; private BaseB(Builder init) { id = init.id; } @Override public String toString() { return "BaseB [id=" + id + "]"; } } @TypeImplementation("c") public static class BaseC extends SomeInterface { public static class Builder { private SubEntity entity; private String id; public Builder withSubEntity(SubEntity entity) { this.entity = entity; return this; } public Builder withId(String id) { this.id = id; return this; } public BaseC build() { return new BaseC(this); } } private final SubEntity entity; private final String id; private BaseC(Builder init) { this.entity = init.entity; this.id = init.id; } @Override public String toString() { return "BaseC [entity=" + entity + ", id=" + id + "]"; } } @TypeImplementation("d") public static class BaseD extends SomeInterface { private final String s; private final Long l; private final Boolean b; private final Double d; private final Integer i; private final Properties p; private final String id; public static class Builder { private String s; private Long l; private Boolean b; private Double d; private Integer i; private Properties p; private String id; public Builder withId(String id) { this.id = id; return this; } public Builder withString(String s) { this.s = s; return this; } public Builder withLong(long l) { this.l = l; return this; } public Builder withInteger(int i) { this.i = i; return this; } public Builder withDouble(double d) { this.d = d; return this; } public Builder withBoolean(boolean b) { this.b = b; return this; } public Builder withProperties(Properties props) { this.p = props; return this; } public BaseD build() { return new BaseD(this); } } private BaseD(Builder init) { this.s = init.s; this.l = init.l; this.b = init.b; this.i = init.i; this.d = init.d; this.p = init.p; this.id = init.id; } public String getString() { return this.s; } public Properties getProperties() { return this.p; } @Override public String toString() { return "BaseD [id=" + id + ", s=" + s + ", l=" + l + ", b=" + b + ", d=" + d + ", i=" + i + ", p=" + p + "]"; } } public static class MyService { @Inject public MyService(final ComponentManager<SomeInterface> manager) throws ComponentCreationException, ComponentAlreadyExistsException { SomeInterface if1 = manager.get("id1"); LOG.info(if1.toString()); SomeInterface if2 = manager.get("id2"); LOG.info(if2.toString()); Properties prop2 = new Properties(); prop2.put("type", "b"); prop2.put("prop1", "v1"); prop2.put("prop2", "v2"); // SomeInterface base3 = manager.get(new PropertyMapper("id2", prop2.getProperty("type"), prop2)); // LOG.info(base3.toString()); } } public static class MyServiceWithNamedComponent { @Inject public MyServiceWithNamedComponent(@Named("id1") SomeInterface iface) { } } @Test public void testNamed() { // 1. Bootstrap on startup // 2. Load by 'id' // 3. Map with prefix final Properties props = new Properties(); props.put("id1.some.type", "a"); props.put("id1.some.prop1", "v1"); Injector injector = Guice.createInjector( new PropertiesConfigurationModule(props), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseA.class) .implementation(BaseB.class) .implementation(BaseC.class) .implementation(BaseD.class) .build(SomeInterface.class) ); install(new ComponentModuleBuilder<Policy>() .implementation(PolicyA.class) .implementation(PolicyB.class) .build(Policy.class)); } }, new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .named("id1") .build(SomeInterface.class) ); bind(MyServiceWithNamedComponent.class); } } ); MyServiceWithNamedComponent service = injector.getInstance(MyServiceWithNamedComponent.class); } @Test public void testProperies() throws Exception { // 1. Bootstrap on startup // 2. Load by 'id' // 3. Map with prefix final Properties props = new Properties(); // Properties is NOT a map props.put("id1.some.type", "d"); props.put("id1.some.properties", "simplevalue"); // Properties not provided props.put("id2.some.type", "d"); // Properties is a map props.put("id3.some.type", "d"); props.put("id3.some.properties.a", "a"); props.put("id3.some.properties.b.c","bc"); props.put("id3.some.properties.d", "true"); props.put("id3.some.properties.e", "123"); ConfigurationManager.loadProperties(props); Injector injector = Guice.createInjector( new ArchaiusConfigurationModule(), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseD.class) .build(SomeInterface.class) ); } } ); ComponentManager<SomeInterface> ifmanager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); BaseD iface2 = (BaseD)ifmanager.get("id2"); BaseD iface3 = (BaseD)ifmanager.get("id3"); LOG.info(iface2.toString()); LOG.info(iface3.toString()); try { // TODO: Need to fix this unit test BaseD iface1 = (BaseD)ifmanager.get("id1"); LOG.info(iface1.toString()); // Assert.fail(); } catch (Exception e) { } } public static class SomeInterfaceProvider implements Provider<SomeInterface> { @Override public SomeInterface get() { LOG.info("hi"); return null; } } @Test public void testProperties() throws Exception { // 1. Bootstrap on startup // 2. Load by 'id' // 3. Map with prefix final Properties props = new Properties(); props.put("id1.some.type", "d"); props.put("id1.some.string", "str"); props.put("id1.some.long", "1"); props.put("id1.some.boolean", "true"); props.put("id1.some.integer", "2"); props.put("id1.some.double", "2.1"); props.put("id1.some.dyn1", "dyn1_value"); props.put("id1.some.dyn2", "dyn2_value"); props.put("id1.some.policy.type", "pa"); props.put("id1.some.policy.arg2", "pa_arg2"); props.put("id2.some.type", "c"); props.put("id2.some.subEntity.str", "id2_subEntity_str"); Injector injector = Guice.createInjector( new PropertiesConfigurationModule(props), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseA.class) .implementation(BaseB.class) .implementation(BaseC.class) .implementation(BaseD.class) .build(SomeInterface.class) ); install(new ComponentModuleBuilder<Policy>() .implementation(PolicyA.class) .implementation(PolicyB.class) .build(Policy.class)); bind(SomeInterface.class) .annotatedWith(Names.named("id1")) .toProvider(SomeInterfaceProvider.class); } }, new AbstractModule() { @Override protected void configure() { bind(MyService.class); } } ); MyService service = injector.getInstance(MyService.class); ComponentManager<SomeInterface> ifmanager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); SomeInterface if1 = ifmanager.get("id1"); LOG.info(if1.toString()); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn1", "dyn1_value_new"); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn2", "dyn2_value_new"); // Map<Object, Object> props2 = ConfigurationConverter.getMap(ConfigurationManager.getConfigInstance()); // for (Entry<Object, Object> prop : props2.entrySet()) { // LOG.info(prop.getKey() + " = " + prop.getValue()); // } LOG.info(if1.toString()); } @Test @Ignore public void testJson() throws Exception { Injector injector = Guice.createInjector( new PropertiesConfigurationModule(new Properties()), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseA.class) .implementation(BaseB.class) .implementation(BaseC.class) .build(SomeInterface.class) ); install(new ComponentModuleBuilder<Policy>() .implementation(PolicyA.class) .implementation(PolicyB.class) .build(Policy.class)); bind(SomeInterface.class) .annotatedWith(Names.named("id1")) .toProvider(SomeInterfaceProvider.class); } }, new AbstractModule() { @Override protected void configure() { bind(MyService.class); } } ); // MyService service = injector.getInstance(MyService.class); ComponentManager<SomeInterface> ifmanager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); // 1. Bootstrap on startup // 2. Load by 'id' // 3. Map with prefix ObjectMapper mapper = new ObjectMapper(); ObjectNode node = mapper.createObjectNode(); node.put("type", "a"); node.put("prop1", "v1"); node.put("prop2", "v2"); node.put("dyn1", "dyn1_value"); node.put("dyn2", "dyn2_value"); ObjectNode policy = mapper.createObjectNode(); policy.put("type", "pa"); policy.put("arg1", "pa_arg2"); node.put("policy", policy); SomeInterface if1 = ifmanager.get("id1"); LOG.info(if1.toString()); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn1", "dyn1_value_new"); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn2", "dyn2_value_new"); // Map<Object, Object> props2 = ConfigurationConverter.getMap(ConfigurationManager.getConfigInstance()); // for (Entry<Object, Object> prop : props2.entrySet()) { // LOG.info(prop.getKey() + " = " + prop.getValue()); // } LOG.info(if1.toString()); } @Test @Ignore public void testRegisterBeforeGet() throws Exception { Injector injector = Guice.createInjector( new PropertiesConfigurationModule(new Properties()), new SomeInterfaceModule() ); ComponentManager<SomeInterface> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); manager.add("a", new SomeInterface() {}); // final AtomicInteger changed = new AtomicInteger(); // ListenableReference<SomeInterface> ref = manager.get("a"); // ref.change(new ReferenceChangeListener<SomeInterface>() { // @Override // public void removed() { // } // // @Override // public void changed(SomeInterface newComponent) { // changed.incrementAndGet(); // } // }); // // ref.get(); // Assert.assertEquals(1, changed.get()); } @Test @Ignore public void testRegisterAfterGet() throws Exception { Injector injector = Guice.createInjector( new PropertiesConfigurationModule(new Properties()), new SomeInterfaceModule() ); ComponentManager<SomeInterface> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); manager.add("a", new SomeInterface() {}); // final AtomicInteger changed = new AtomicInteger(); // ListenableReference<SomeInterface> ref = manager.get("a"); // ref.get(); // ref.change(new ReferenceChangeListener<SomeInterface>() { // @Override // public void removed() { // } // // @Override // public void changed(SomeInterface newComponent) { // changed.incrementAndGet(); // } // }); // Assert.assertEquals(0, changed.get()); } @Test @Ignore public void testChangedComponent() throws Exception { Injector injector = Guice.createInjector( new PropertiesConfigurationModule(new Properties()), new SomeInterfaceModule() ); ComponentManager<SomeInterface> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); manager.add("a", new SomeInterface() {}); // final AtomicInteger changed = new AtomicInteger(); // ListenableReference<SomeInterface> ref = manager.get("a"); // ref.change(new ReferenceChangeListener<SomeInterface>() { // @Override // public void removed() { // } // // @Override // public void changed(SomeInterface newComponent) { // changed.incrementAndGet(); // } // }); // manager.replace("a", new SomeInterface() {}); // Assert.assertEquals(2, changed.get()); } @Test @Ignore public void testRemovedComponent() throws Exception { Injector injector = Guice.createInjector( new PropertiesConfigurationModule(new Properties()), new SomeInterfaceModule() ); ComponentManager<SomeInterface> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); manager.add("a", new SomeInterface() {}); // final AtomicBoolean changed = new AtomicBoolean(false); // ListenableReference<SomeInterface> ref = manager.get("a"); // ref.change(new ReferenceChangeListener<SomeInterface>() { // @Override // public void removed() { // changed.set(true); // } // // @Override // public void changed(SomeInterface newComponent) { // } // }); // ref.get(); // manager.remove("a"); // Assert.assertTrue(changed.get()); } }
2,085
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/archaius/ArchaiusTypeConfigurationResolverTest.java
package com.netflix.fabricator.archaius; import java.util.Map; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import com.netflix.config.ConfigurationManager; import com.netflix.fabricator.ConfigurationNode; public class ArchaiusTypeConfigurationResolverTest { @Test public void testReadAll() { Properties properties = new Properties(); properties.put("id1.sometype.a", "_a1"); properties.put("id2.sometype", "{\"type\":\"_type\",\"a\":\"_a2\"}"); properties.put("id3.sometype", "{\"type\":\"_type\",\"a\":\"_a3\"}"); System.out.println(properties); properties.put("id1.someothertype.a", "_a"); ConfigurationManager.loadProperties(properties); ArchaiusTypeConfigurationResolver resolver = new ArchaiusTypeConfigurationResolver(null); Map<String, ConfigurationNode> someTypeConfigs = resolver.getConfigurationFactory("sometype").getAllConfigurations(); Assert.assertEquals(3, someTypeConfigs.keySet().size()); Assert.assertEquals("_a1", someTypeConfigs.get("id1").getChild("a").getValue(String.class)); Assert.assertEquals("_a2", someTypeConfigs.get("id2").getChild("a").getValue(String.class)); Assert.assertEquals("_a3", someTypeConfigs.get("id3").getChild("a").getValue(String.class)); Map<String, ConfigurationNode> someOtherTypeConfigs = resolver.getConfigurationFactory("someothertype").getAllConfigurations(); Assert.assertEquals(1, someOtherTypeConfigs.keySet().size()); Assert.assertEquals("_a", someOtherTypeConfigs.get("id1").getChild("a").getValue(String.class)); } }
2,086
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component/ComponentManagerTest.java
package com.netflix.fabricator.component; import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Supplier; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.Provider; import com.google.inject.Scopes; import com.google.inject.TypeLiteral; import com.google.inject.name.Named; import com.google.inject.name.Names; import com.netflix.config.ConfigurationManager; import com.netflix.fabricator.ComponentType; import com.netflix.fabricator.annotations.Type; import com.netflix.fabricator.annotations.TypeImplementation; import com.netflix.fabricator.archaius.ArchaiusConfigurationModule; import com.netflix.fabricator.component.exception.ComponentAlreadyExistsException; import com.netflix.fabricator.component.exception.ComponentCreationException; import com.netflix.fabricator.guice.ComponentModuleBuilder; import com.netflix.fabricator.properties.PropertiesConfigurationModule; import com.netflix.fabricator.supplier.ListenableSupplier; import com.netflix.fabricator.supplier.SupplierWithDefault; /** * Test Driven development for Beaver library. * Prerequisites: * Environment: * 1. Guice injector environment to inject anything * 2. Archaius * 3. Jackson * 4. Properties files * Code: * 1. Classes with builder pattern built in. * 1.1. Different builder classes with focuses on different patterns. * 1.1.1. Simple properties * 1.1.1.1. Supplier argument type. * 1.1.1.2. Simple property type. * 1.1.1.3. Composite properties type. * 1.1.2. Supplier properties. * 1.1.2.1. With default values. * 1.1.2.2. Without default values. * 1.1.3. Compostite properties * 1.1.3.1. Argument type has to be composite. * 2. Prebuilt objects can be directly retrieved without construction * 3. Negative cases */ public class ComponentManagerTest { private static final Logger logger = LoggerFactory.getLogger(ComponentManagerTest.class); /** * Example of a subentity * */ public static class SubEntity { public static class Builder { private String str; public Builder withStr(String str) { this.str = str; return this; } public SubEntity build() { return new SubEntity(this); } } private final String str; private SubEntity(Builder init) { this.str = init.str; } public String getString() { return str; } @Override public String toString() { return "SubEntity [str=" + str + "]"; } } /** * Interface for a policy * @author elandau * */ @Type("policy") public static interface Policy { } /** * Implementation of a policy with one String arg * * @author elandau */ @TypeImplementation("pa") public static class PolicyA implements Policy { private final String s; private final Long l; private final Boolean b; private final Double d; private final Integer i; public static class Builder { private String s; private Long l; private Boolean b; private Double d; private Integer i; public Builder withString(String s) { this.s = s; return this; } public Builder withLong(Long l) { this.l = l; return this; } public Builder withInteger(Integer i) { this.i = i; return this; } public Builder withDouble(Double d) { this.d = d; return this; } public Builder withBoolean(Boolean b) { this.b = b; return this; } public PolicyA build() { return new PolicyA(this); } } private PolicyA(Builder init) { this.s = init.s; this.l = init.l; this.b = init.b; this.i = init.i; this.d = init.d; } public String getString() { return this.s; } @Override public String toString() { return "PolicyA [s=" + s + ", l=" + l + ", b=" + b + ", d=" + d + ", i=" + i + "]"; } } /** * A plicy with one string arg and a supplier * @author elandau * */ @TypeImplementation("pb") public static class PolicyB implements Policy { private final Supplier<String> arg1; public static class Builder { private final SupplierWithDefault<String> arg1 = SupplierWithDefault.from("abc"); public Builder withArg1(String arg1) { this.arg1.setValue(arg1); return this; } public Builder withArg1(Supplier<String> arg1) { this.arg1.addOverride(arg1); return this; } public PolicyB build() { return new PolicyB(this); } } private PolicyB(Builder init) { this.arg1 = init.arg1; } @Override public String toString() { return "PolicyB [arg1=" + arg1 + "]"; } } /** * * @author elandau * */ @Type("some") public static abstract class SomeInterface { } /** * * @author elandau * */ @TypeImplementation("a") public static class BaseA extends SomeInterface { public static class Builder { private String id; private String prop1; private Policy policy; private final SupplierWithDefault<String> dyn1 = new SupplierWithDefault<String>("dyn1_default"); private final SupplierWithDefault<String> dyn2 = new SupplierWithDefault<String>("dyn2_default"); public Builder withId(String id) { this.id = id; return this; } public Builder withProp1(String prop1) { this.prop1 = prop1; return this; } public Builder withPolicy(Policy policy) { this.policy = policy; return this; } public Builder withDyn1(Supplier<String> supplier) { logger.info("dyn1=" + supplier.get()); this.dyn1.addOverride(supplier); return this; } public Builder withDyn2(ListenableSupplier<String> supplier) { logger.info("dyn2=" + supplier.get()); this.dyn2.setSource(supplier); return this; } public BaseA build() { return new BaseA(this); } } private final String id; private final String prop1; private final Policy policy; private final Supplier<String> dyn1; private final ListenableSupplier<String> dyn2; private BaseA(Builder init) { this.id = init.id; this.prop1 = init.prop1; this.policy = init.policy; this.dyn1 = init.dyn1; this.dyn2 = init.dyn2; this.dyn2.onChange(new Function<String, Void>() { public Void apply(@Nullable String input) { logger.info("Value has changed to : " + input); return null; } }); } public Policy getPolicy() { return policy; } @Override public String toString() { return "BaseA [id=" + id + ", prop1=" + prop1 + ", policy=" + policy + ", dyn1=" + dyn1.get() + ", dyn2=" + dyn2.get() + "]"; } } /** * * @author elandau * */ @TypeImplementation("b") public static class BaseB extends SomeInterface { public static class Builder { private String id; public Builder withId(String id) { this.id = id; return this; } public BaseB build() { return new BaseB(this); } } private final String id; private BaseB(Builder init) { id = init.id; } @Override public String toString() { return "BaseB [id=" + id + "]"; } } @TypeImplementation("c") public static class BaseC extends SomeInterface { public static class Builder { private SubEntity entity; private String id; public Builder withSubEntity(SubEntity entity) { this.entity = entity; return this; } public Builder withId(String id) { this.id = id; return this; } public BaseC build() { return new BaseC(this); } } private final SubEntity entity; private final String id; private BaseC(Builder init) { this.entity = init.entity; this.id = init.id; } @Override public String toString() { return "BaseC [entity=" + entity + ", id=" + id + "]"; } } @TypeImplementation("d") public static class BaseD extends SomeInterface { private final String s; private final Long l; private final Boolean b; private final Double d; private final Integer i; private final Properties p; private final String id; public static class Builder { private String s; private Long l; private Boolean b; private Double d; private Integer i; private Properties p; private String id; public Builder() { } public Builder withId(String id) { this.id = id; return this; } public Builder withString(String s) { this.s = s; return this; } public Builder withLong(long l) { this.l = l; return this; } public Builder withInteger(int i) { this.i = i; return this; } public Builder withDouble(double d) { this.d = d; return this; } public Builder withBoolean(boolean b) { this.b = b; return this; } public Builder withProperties(Properties props) { this.p = props; return this; } public BaseD build() { return new BaseD(this); } } private BaseD(Builder init) { this.s = init.s; this.l = init.l; this.b = init.b; this.i = init.i; this.d = init.d; this.p = init.p; this.id = init.id; } public String getString() { return this.s; } public Properties getProperties() { return this.p; } @Override public String toString() { return "BaseD [id=" + id + ", s=" + s + ", l=" + l + ", b=" + b + ", d=" + d + ", i=" + i + ", p=" + p + "]"; } } public static class MyService { private SomeInterface if1; private SomeInterface if2; @Inject public MyService(final ComponentManager<SomeInterface> manager) throws ComponentCreationException, ComponentAlreadyExistsException { if1 = manager.get("id1"); if2 = manager.get("id2"); } } public static class MyServiceWithNamedComponent { private SomeInterface if1; private SomeInterface if2; @Inject public MyServiceWithNamedComponent(@Named("id1") SomeInterface if1, @Named("id2") SomeInterface if2) { this.if1 = if1; this.if2 = if2; } } @Before public void setUp() throws Exception { } public static class SomeInterfaceModule extends AbstractModule { @Override protected void configure() { bind(new TypeLiteral<ComponentManager<SomeInterface>>(){}) .to(new TypeLiteral<SynchronizedComponentManager<SomeInterface>>(){}) .in(Scopes.SINGLETON); bind(new TypeLiteral<ComponentType<SomeInterface>>(){}) .toInstance(new ComponentType<SomeInterface>("some")); install(new ComponentModuleBuilder<SomeInterface>() .build(SomeInterface.class)); } } @Test public void testEmbeddedEntity() throws Exception { final Properties props = new Properties(); props.put("id1.some.type", "a"); props.put("id1.some.string", "str"); props.put("id1.some.dyn1", "dyn1_value"); props.put("id1.some.dyn2", "dyn2_value"); props.put("id1.some.policy.type", "pb"); props.put("id1.some.policy.arg1", "pb_arg1"); Injector injector = Guice.createInjector( new PropertiesConfigurationModule(props), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseA.class) .build(SomeInterface.class) ); install(new ComponentModuleBuilder<Policy>() .implementation(PolicyA.class) .implementation(PolicyB.class) .build(Policy.class)); } }, new AbstractModule() { @Override protected void configure() { bind(MyService.class); } } ); Assert.assertNotNull(injector.getBinding(Key.get(new TypeLiteral<Map<String, Provider<ComponentFactory<Policy>>>>() {}))); Assert.assertNotNull(injector.getBinding(Key.get(new TypeLiteral<Map<String, Provider<ComponentFactory<Policy>>>>() {}))); ComponentManager<SomeInterface> ifmanager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); BaseA if1 = (BaseA)ifmanager.get("id1"); logger.info("get id4 from manager: " + if1.toString()); Assert.assertNotNull(if1.getPolicy()); } @Test public void testComponentManager() throws ComponentCreationException, ComponentAlreadyExistsException, InterruptedException { final Properties props = new Properties(); props.setProperty("id1.some.type", "d"); props.setProperty("id1.some.string", "str"); props.setProperty("id1.some.long", "1"); props.setProperty("id1.some.boolean", "true"); props.setProperty("id1.some.integer", "2"); props.setProperty("id1.some.double", "2.1"); props.setProperty("id1.some.properties.a", "_a"); props.setProperty("id1.some.properties.b", "_b"); props.setProperty("id2.some.type", "c"); props.setProperty("id2.some.subEntity.str", "id2_subEntity_str"); props.setProperty("id3.some.type", "b"); props.setProperty("id4.some.type", "a"); props.setProperty("id4.some.string", "str"); props.setProperty("id4.some.dyn1", "dyn1_value"); props.setProperty("id4.some.dyn2", "dyn2_value"); props.setProperty("id4.some.policy.type", "pb"); props.setProperty("id4.some.policy.arg1", "pb_arg1"); ConfigurationManager.getConfigInstance(); ConfigurationManager.loadProperties(props); String value = ConfigurationManager.getConfigInstance().getString("id1.some.type"); Injector injector = Guice.createInjector( new ArchaiusConfigurationModule(), new SomeInterfaceModule(), new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .implementation(BaseA.class) .implementation(BaseB.class) .implementation(BaseC.class) .implementation(BaseD.class) .build(SomeInterface.class) ); install(new ComponentModuleBuilder<Policy>() .implementation(PolicyA.class) .implementation("pb", PolicyB.class) .build(Policy.class)); } }, new AbstractModule() { @Override protected void configure() { install(new ComponentModuleBuilder<SomeInterface>() .named("id1") .named("id2") .build(SomeInterface.class) ); } } ); TimeUnit.SECONDS.sleep(1); SomeInterface si1 = injector.getInstance(Key.get(SomeInterface.class, Names.named("id1"))); Assert.assertNotNull(si1); ComponentManager<SomeInterface> ifmanager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeInterface>>() {})); BaseD if1 = (BaseD)ifmanager.get("id1"); logger.info("get id1 from manager: " + if1.toString()); Assert.assertEquals(BaseD.class, if1.getClass()); Assert.assertNotNull(if1.getProperties()); Assert.assertEquals(2, if1.getProperties().size()); SomeInterface if2 = ifmanager.get("id2"); logger.info("get id2 from manager: " + if2.toString()); Assert.assertEquals(BaseC.class, if2.getClass()); SomeInterface if3 = ifmanager.get("id3"); logger.info("get id3 from manager: " + if3.toString()); Assert.assertEquals(BaseB.class, if3.getClass()); SomeInterface if4 = ifmanager.get("id4"); BaseA a = (BaseA)if4; Assert.assertEquals(PolicyB.class, a.getPolicy().getClass()); Assert.assertEquals("pb_arg1", ((PolicyB)a.getPolicy()).arg1.get()); logger.info("get id4 from manager: " + if4.toString()); Assert.assertEquals(BaseA.class, if4.getClass()); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn1", "dyn1_value_new"); ConfigurationManager.getConfigInstance().setProperty("id1.some.dyn2", "dyn2_value_new"); logger.info("if4 after setProperty: " + if4.toString()); MyService service = injector.getInstance(MyService.class); Assert.assertEquals(if1, service.if1); Assert.assertEquals(if2, service.if2); MyServiceWithNamedComponent serviceWithNamedComponent = injector.getInstance(MyServiceWithNamedComponent.class); Assert.assertEquals(if1, serviceWithNamedComponent.if1); Assert.assertEquals(if2, serviceWithNamedComponent.if2); } }
2,087
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component/mapping/Foo.java
package com.netflix.fabricator.component.mapping; public interface Foo { public <T> String call(T entity) throws Exception; }
2,088
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component/mapping/FooModule.java
package com.netflix.fabricator.component.mapping; import com.google.inject.AbstractModule; import com.google.inject.name.Names; public class FooModule extends AbstractModule { @Override protected void configure() { bind(Foo.class).annotatedWith(Names.named("string")).toInstance(new FooImpl("string")); bind(Foo.class).annotatedWith(Names.named("base64")).toInstance(new FooImpl("base64")); bind(Foo.class).annotatedWith(Names.named("jackson")).toInstance(new FooImpl("jackson")); } }
2,089
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component/mapping/NamedDeserializerTest.java
package com.netflix.fabricator.component.mapping; import java.util.Properties; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; import com.google.inject.name.Names; import com.netflix.config.ConfigurationManager; import com.netflix.fabricator.annotations.Type; import com.netflix.fabricator.annotations.TypeImplementation; import com.netflix.fabricator.archaius.ArchaiusConfigurationModule; import com.netflix.fabricator.component.ComponentManager; import com.netflix.fabricator.component.SynchronizedComponentManager; import com.netflix.fabricator.guice.ComponentModuleBuilder; public class NamedDeserializerTest { private static final Logger LOG = LoggerFactory.getLogger(NamedDeserializerTest.class); @Type("foo") public static interface SomeType { public String serialize(Object obj) throws Exception; } @TypeImplementation("impl") public static class SomeTypeImpl1 implements SomeType { public static class Builder { private Foo serializer; public Builder withSerializer(Foo serializer) { this.serializer = serializer; return this; } public SomeTypeImpl1 build() { return new SomeTypeImpl1(this); } } public static Builder builder() { return new Builder(); } private final Foo serializer; public SomeTypeImpl1(Builder builder) { this.serializer = builder.serializer; } public String serialize(Object obj) throws Exception { return serializer.call(obj); } } @Test public void testConfiguredDeserializer() throws Exception { final Properties props = new Properties(); props.put("1.foo.type", "impl"); props.put("1.foo.serializer", "jackson"); props.put("2.foo.type", "impl"); props.put("2.foo.serializer", "base64"); props.put("3.foo.type", "impl"); props.put("3.foo.serializer", "string"); props.put("4.foo.type", "impl"); props.put("4.foo.serializer", "custom"); ConfigurationManager.loadProperties(props); Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { install(new ArchaiusConfigurationModule()); install(new FooModule()); install(new ComponentModuleBuilder<SomeType>() .manager(SynchronizedComponentManager.class) .implementation(SomeTypeImpl1.class) .build(SomeType.class)); bind(Foo.class).annotatedWith(Names.named("custom")).toInstance(new Foo() { @Override public <T> String call(T entity) throws Exception { return "custom"; } }); } }); ComponentManager<SomeType> manager = injector.getInstance(Key.get(new TypeLiteral<ComponentManager<SomeType>>() {})); SomeType o1 = manager.get("1"); SomeType o2 = manager.get("2"); SomeType o3 = manager.get("3"); SomeType o4 = manager.get("4"); LOG.info(o1.serialize("foo")); LOG.info(o2.serialize("foo")); LOG.info(o3.serialize("foo")); LOG.info(o4.serialize("foo")); } }
2,090
0
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component
Create_ds/fabricator/fabricator-archaius/src/test/java/com/netflix/fabricator/component/mapping/FooImpl.java
package com.netflix.fabricator.component.mapping; public class FooImpl implements Foo { private String constant; public FooImpl(String constant) { this.constant = constant; } @Override public <T> String call(T entity) throws Exception { return constant + entity; } }
2,091
0
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator/archaius/ArchaiusTypeConfigurationResolver.java
package com.netflix.fabricator.archaius; import java.util.Iterator; import java.util.Map; import javax.inject.Inject; import javax.inject.Singleton; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.lang.StringUtils; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Joiner; import com.google.common.collect.Maps; import com.netflix.config.ConfigurationManager; import com.netflix.fabricator.ConfigurationNode; import com.netflix.fabricator.ComponentConfigurationResolver; import com.netflix.fabricator.TypeConfigurationResolver; import com.netflix.fabricator.jackson.JacksonComponentConfiguration; /** * Main configuration access using Archaius as the configuration source. * Configuration for type and key follows a specific naming convention * unless otherwise specified via a MapBinding of type (string) to a * specific ConfigurationFactory. * * The naming convention is * ${key}.${type} * * Where * 'key' is the unique id for the instance of the specified type * 'type' is the component interface type and not the type of a specified * implementation of the compoennt * * @author elandau * */ @Singleton public class ArchaiusTypeConfigurationResolver implements TypeConfigurationResolver { private static String DEFAULT_FORMAT_STRING = "%s.%s"; private static String TYPE_FIELD = "type"; // TODO: Inject this private AbstractConfiguration config = ConfigurationManager.getConfigInstance(); private final Map<String, ComponentConfigurationResolver> overrides; private final ObjectMapper mapper = new ObjectMapper(); @Inject public ArchaiusTypeConfigurationResolver(Map<String, ComponentConfigurationResolver> overrides) { if (overrides == null) { this.overrides = Maps.newHashMap(); } else { this.overrides = overrides; } } @Override public ComponentConfigurationResolver getConfigurationFactory(final String componentType) { ComponentConfigurationResolver factory = overrides.get(componentType); if (factory != null) return factory; return new ComponentConfigurationResolver() { @Override public ConfigurationNode getConfiguration(final String key) { String prefix = String.format(DEFAULT_FORMAT_STRING, key, componentType); if (config.containsKey(prefix)) { String json = Joiner.on(config.getListDelimiter()).join(config.getStringArray(prefix)).trim(); if (!json.isEmpty() && json.startsWith("{") && json.endsWith("}")) { try { JsonNode node = mapper.readTree(json); if (node.get(TYPE_FIELD) == null) throw new Exception("Missing 'type' field"); return new JacksonComponentConfiguration(key, node.get(TYPE_FIELD).asText(), node); } catch (Exception e) { throw new RuntimeException( String.format("Unable to parse json from '%s'. (%s)", prefix, StringUtils.abbreviate(json, 256)), e); } } } String typeField = Joiner.on(".").join(prefix, TYPE_FIELD); String typeValue = config.getString(typeField); if (componentType == null) { throw new RuntimeException(String.format("Type for '%s' not specified '%s'", typeField, componentType)); } return new ArchaiusComponentConfiguration( key, typeValue, config, prefix); } @Override public Map<String, ConfigurationNode> getAllConfigurations() { Map<String, ConfigurationNode> configs = Maps.newHashMap(); Iterator<String> keys = config.getKeys(); while (keys.hasNext()) { String key = keys.next(); String[] parts = StringUtils.split(key, "."); if (parts.length > 1) { String type = parts[1]; if (type.equals(componentType)) { String id = parts[0]; if (!configs.containsKey(id)) { configs.put(id, getConfiguration(id)); } } } } return configs; } }; } }
2,092
0
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator/archaius/ArchaiusComponentConfiguration.java
package com.netflix.fabricator.archaius; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.apache.commons.configuration.AbstractConfiguration; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.netflix.config.ConfigurationManager; import com.netflix.config.DynamicProperty; import com.netflix.fabricator.ConfigurationNode; import com.netflix.fabricator.properties.AbstractPropertiesComponentConfiguration; import com.netflix.fabricator.supplier.ListenableSupplier; public class ArchaiusComponentConfiguration extends AbstractPropertiesComponentConfiguration { private static final Logger LOG = LoggerFactory.getLogger(ArchaiusComponentConfiguration.class); public static ArchaiusComponentConfiguration forPrefix(String prefix) { AbstractConfiguration config = ConfigurationManager.getConfigInstance(); String type = config.getString(prefix + "type"); String id = StringUtils.substringAfterLast(prefix, "."); return new ArchaiusComponentConfiguration(id, type, config, prefix); } private final AbstractConfiguration config; public ArchaiusComponentConfiguration(String id, String type, AbstractConfiguration config, String prefix) { super(id, type, prefix); this.config = config; } public ArchaiusComponentConfiguration(String id, String type, AbstractConfiguration config) { super(id, type); this.config = config; } public static abstract class DynamicListenableSupplier<T> implements ListenableSupplier<T> { private final DynamicProperty prop; DynamicListenableSupplier(DynamicProperty prop) { this.prop = prop; } @Override public void onChange(final Function<T, Void> func) { prop.addCallback(new Runnable() { @Override public void run() { func.apply(get()); } }); } } @SuppressWarnings("unchecked") @Override public <T> ListenableSupplier<T> getDynamicValue(Class<T> type) { final DynamicProperty prop = DynamicProperty.getInstance(getFullName()); if ( String.class.isAssignableFrom(type) ) { return (ListenableSupplier<T>) new DynamicListenableSupplier<String>(prop) { @Override public String get() { return prop.getString(); } }; } else if ( Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type) || boolean.class.equals(type)) { return (ListenableSupplier<T>) new DynamicListenableSupplier<Boolean>(prop) { @Override public Boolean get() { return prop.getBoolean(); } }; } else if ( Integer.class.isAssignableFrom(type) || Integer.TYPE.isAssignableFrom(type) || int.class.equals(type)) { return (ListenableSupplier<T>) new DynamicListenableSupplier<Integer>(prop) { @Override public Integer get() { return prop.getInteger(); } }; } else if ( Long.class.isAssignableFrom(type) || Long.TYPE.isAssignableFrom(type) || long.class.equals(type)) { return (ListenableSupplier<T>) new DynamicListenableSupplier<Long>(prop) { @Override public Long get() { return prop.getLong(); } }; } else if ( Double.class.isAssignableFrom(type) || Double.TYPE.isAssignableFrom(type) || double.class.equals(type)) { return (ListenableSupplier<T>) new DynamicListenableSupplier<Double>(prop) { @Override public Double get() { return prop.getDouble(); } }; } else if ( Properties.class.isAssignableFrom(type)) { return (ListenableSupplier<T>) new DynamicListenableSupplier<Properties>(prop) { @Override public Properties get() { if (config.containsKey(getFullName())) { throw new RuntimeException(getFullName() + " is not a root for a properties structure"); } String prefix = getFullName(); Properties result = new Properties(); for (String prop : Lists.newArrayList(config.getKeys(prefix))) { result.setProperty(prop, config.getString(prop)); } return result; } }; } else { LOG.warn(String.format("Unknown type '%s' for property '%s'", type.getCanonicalName(), getFullName())); } return null; } @Override public ConfigurationNode getChild(String name) { String fullName = Joiner.on(".").skipNulls().join(getFullName(), name); return new ArchaiusComponentConfiguration( name, config.getString(Joiner.on(".").skipNulls().join(fullName, "type")), config, fullName); } @Override public boolean isSingle() { if (config.containsKey(getFullName())) { return true; } return false; // TODO: Look for sub properties } @Override public boolean hasChild(String propertyName) { return true; } @Override public Set<String> getUnknownProperties(Set<String> supportedProperties) { // TODO: return Collections.emptySet(); } @SuppressWarnings("unchecked") @Override public <T> T getValue(Class<T> type) { String key = getFullName(); if ( String.class.isAssignableFrom(type) ) { return (T) config.getString(key); } else if ( Boolean.class.isAssignableFrom(type) || Boolean.TYPE.isAssignableFrom(type) || boolean.class.equals(type)) { return (T) config.getBoolean(key, null); } else if ( Integer.class.isAssignableFrom(type) || Integer.TYPE.isAssignableFrom(type) || int.class.equals(type)) { return (T) config.getInteger(key, null); } else if ( Long.class.isAssignableFrom(type) || Long.TYPE.isAssignableFrom(type) || long.class.equals(type)) { return (T) config.getLong(key, null); } else if ( Double.class.isAssignableFrom(type) || Double.TYPE.isAssignableFrom(type) || double.class.equals(type)) { return (T) config.getDouble(key, null); } else if ( Short.class.isAssignableFrom(type) || Short.TYPE.isAssignableFrom(type) || short.class.equals(type)) { return (T) config.getShort(key, null); } else if ( Float.class.isAssignableFrom(type) || Float.TYPE.isAssignableFrom(type) || float.class.equals(type)) { return (T) config.getFloat(key, null); } else if ( BigDecimal.class.isAssignableFrom(type) ) { return (T) config.getBigDecimal(key, null); } else if ( BigInteger.class.isAssignableFrom(type) ) { return (T) config.getBigInteger(key, null); } else if ( Properties.class.isAssignableFrom(type)) { String prefix = getFullName(); Properties result = new Properties(); Configuration sub = config.subset(prefix); Iterator<String> iter = sub.getKeys(); while (iter.hasNext()) { String propName = iter.next(); result.setProperty(propName, sub.getString(propName)); } return (T) result; } else { LOG.warn(String.format("Unknown type '%s' for property '%s'", type.getCanonicalName(), getFullName())); return null; } } }
2,093
0
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-archaius/src/main/java/com/netflix/fabricator/archaius/ArchaiusConfigurationModule.java
package com.netflix.fabricator.archaius; import javax.inject.Singleton; import com.google.inject.AbstractModule; import com.google.inject.multibindings.MapBinder; import com.netflix.fabricator.ComponentConfigurationResolver; import com.netflix.fabricator.TypeConfigurationResolver; @Singleton public class ArchaiusConfigurationModule extends AbstractModule { @Override protected void configure() { MapBinder.newMapBinder(binder(), String.class, ComponentConfigurationResolver.class); bind(TypeConfigurationResolver.class).to(ArchaiusTypeConfigurationResolver.class); } // These implementations of hashCode and equals guarantee that Guice will dedup modules that installed multiple times @Override public int hashCode() { return getClass().hashCode(); } @Override public boolean equals(Object other) { return getClass().equals(other.getClass()); } }
2,094
0
Create_ds/fabricator/fabricator-core/src/test/java/com/netflix
Create_ds/fabricator/fabricator-core/src/test/java/com/netflix/fabricator/JacksonConfigurationSourceTest.java
package com.netflix.fabricator; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.netflix.fabricator.jackson.JacksonComponentConfiguration; public class JacksonConfigurationSourceTest { private static String json = "{\"properties\":{" + " \"a\":\"_a\"," + " \"b\":\"_b\"," + " \"c\":\"_c\"" + "}" + "}"; @Test public void test() throws Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(json); Properties prop1 = new Properties(); prop1.setProperty("a", "_a"); prop1.setProperty("b", "_b"); prop1.setProperty("c", "_c"); JacksonComponentConfiguration source = new JacksonComponentConfiguration("key1", "type1", node); Properties prop2 = source.getChild("properties").getValue(Properties.class); Assert.assertEquals(prop1, prop2); } }
2,095
0
Create_ds/fabricator/fabricator-core/src/test/java/com/netflix/fabricator
Create_ds/fabricator/fabricator-core/src/test/java/com/netflix/fabricator/properties/PropertiesTypeConfigurationResolverTest.java
package com.netflix.fabricator.properties; import java.util.Map; import java.util.Properties; import org.junit.Assert; import org.junit.Test; import com.netflix.fabricator.ConfigurationNode; public class PropertiesTypeConfigurationResolverTest { @Test public void testReadAll() { Properties properties = new Properties(); properties.put("id1.sometype.a", "_a1"); properties.put("id2.sometype", "{\"type\":\"_type\",\"a\":\"_a2\"}"); properties.put("id3.sometype", "{\"type\":\"_type\",\"a\":\"_a3\"}"); properties.put("id1.someothertype.a", "_a"); PropertiesTypeConfigurationResolver resolver = new PropertiesTypeConfigurationResolver(properties, null); Map<String, ConfigurationNode> someTypeConfigs = resolver.getConfigurationFactory("sometype").getAllConfigurations(); Assert.assertEquals(3, someTypeConfigs.keySet().size()); Assert.assertEquals("_a1", someTypeConfigs.get("id1").getChild("a").getValue(String.class)); Assert.assertEquals("_a2", someTypeConfigs.get("id2").getChild("a").getValue(String.class)); Assert.assertEquals("_a3", someTypeConfigs.get("id3").getChild("a").getValue(String.class)); Map<String, ConfigurationNode> someOtherTypeConfigs = resolver.getConfigurationFactory("someothertype").getAllConfigurations(); Assert.assertEquals(1, someOtherTypeConfigs.keySet().size()); Assert.assertEquals("_a", someOtherTypeConfigs.get("id1").getChild("a").getValue(String.class)); } }
2,096
0
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/InjectionSpi.java
package com.netflix.fabricator; import java.lang.reflect.Method; /** * Interface linking fabricator to a depdency injection framework. * * @author elandau */ public interface InjectionSpi { /** * Create an instance of clazz and do any constructor, field or method injections * * @param clazz * @return */ public <T> T getInstance(Class<T> clazz); public PropertyBinder createInjectableProperty( String propertyName, Class<?> argType, Method method); public void injectMembers(Object obj); }
2,097
0
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/Builder.java
package com.netflix.fabricator; /** * Interface definition for a builder pattern. Use then when providing a specific * builder implementation for a type without going through the internal {@link ComponentFactoryProvider). * * @see MyComponentBuilder#builder() * * @author elandau * * @param <T> */ public interface Builder<T> { public T build(); }
2,098
0
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix
Create_ds/fabricator/fabricator-core/src/main/java/com/netflix/fabricator/ComponentType.java
package com.netflix.fabricator; public class ComponentType<T> { private final String type; public ComponentType(String type) { this.type = type; } public String getType() { return type; } public static <T> ComponentType<T> from(String type) { return new ComponentType<T> (type); } }
2,099