1 package org.wikimedia.eventutilities.flink.table.catalog;
2
3 import static org.wikimedia.eventutilities.flink.formats.json.EventJsonFormatOptions.DEFAULT_FORMAT_OPTIONS;
4 import static org.wikimedia.eventutilities.flink.formats.json.EventJsonFormatOptions.FORWARD_OPTIONS;
5 import static org.wikimedia.eventutilities.flink.formats.json.EventJsonFormatOptions.SCHEMA_VERSION;
6 import static org.wikimedia.eventutilities.flink.formats.json.EventJsonFormatOptions.STREAM_NAME;
7 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.DEFAULT_OPTIONS;
8 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.DEFAULT_KAFKA_OPTIONS;
9 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.OVERRIDE_OPTIONS;
10 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.PSEUDO_TABLE_OPTIONS;
11 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.WATERMARK_COLUMN;
12 import static org.wikimedia.eventutilities.flink.table.catalog.EventStreamCatalogFactoryOptions.WATERMARK_DELAY;
13
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Set;
19 import java.util.stream.Collectors;
20
21 import javax.annotation.Nullable;
22
23 import org.apache.flink.configuration.Configuration;
24 import org.apache.flink.streaming.connectors.kafka.table.KafkaConnectorOptions;
25 import org.apache.flink.table.api.Schema;
26 import org.apache.flink.table.catalog.CatalogBaseTable;
27 import org.apache.flink.table.catalog.CatalogTable;
28 import org.apache.flink.table.catalog.CatalogView;
29 import org.apache.flink.table.catalog.ObjectPath;
30 import org.apache.flink.table.catalog.ResolvedCatalogTable;
31 import org.apache.flink.table.catalog.exceptions.CatalogException;
32 import org.apache.flink.table.catalog.exceptions.DatabaseNotExistException;
33 import org.apache.flink.table.catalog.exceptions.TableAlreadyExistException;
34 import org.apache.flink.table.catalog.exceptions.TableNotExistException;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.wikimedia.eventutilities.core.event.EventStream;
38 import org.wikimedia.eventutilities.core.event.EventStreamFactory;
39 import org.wikimedia.eventutilities.flink.formats.json.EventJsonFormatFactory;
40 import org.wikimedia.eventutilities.flink.table.EventTableUtils;
41
42 import com.google.common.collect.MapDifference;
43 import com.google.common.collect.Maps;
44
45 import lombok.SneakyThrows;
46
47 public class EventStreamCatalog extends AbstractEventStreamCatalog {
48
49 private static final Logger LOG = LoggerFactory.getLogger(EventStreamCatalog.class);
50
51 public static final String PLACEHOLDER = "_placeholder_";
52
53 private final List<String> eventSchemasBaseUris;
54
55 private final String eventStreamConfigUri;
56
57 private final Map<String, String> httpRoutes;
58
59 private EventStreamFactory eventStreamFactory;
60
61 private final Map<String, String> options;
62
63 private final EventStreamCatalogConfigurationFactory configurationFactory;
64
65 public EventStreamCatalog(
66 String name,
67 List<String> eventSchemasBaseUris,
68 String eventStreamConfigUri,
69 @Nullable Map<String, String> httpRoutes,
70
71 Map<String, String> options
72 ) {
73 super(name);
74
75 this.eventSchemasBaseUris = eventSchemasBaseUris;
76 this.eventStreamConfigUri = eventStreamConfigUri;
77 this.httpRoutes = httpRoutes;
78
79 Map<String, String> defaultKafkaOptions = new HashMap<>(DEFAULT_KAFKA_OPTIONS);
80 defaultKafkaOptions.put(
81 KafkaConnectorOptions.PROPS_BOOTSTRAP_SERVERS.key(),
82 options.get(KafkaConnectorOptions.PROPS_BOOTSTRAP_SERVERS.key())
83 );
84
85 this.options = options;
86
87 this.configurationFactory = EventStreamCatalogConfigurationFactory.builder()
88 .catalogOptions(this.options)
89 .defaultFormatOptions(DEFAULT_FORMAT_OPTIONS)
90 .defaultKafkaOptions(defaultKafkaOptions)
91 .defaultTableOptions(DEFAULT_OPTIONS)
92 .sharedOptions(FORWARD_OPTIONS)
93 .pseudoTableOptions(PSEUDO_TABLE_OPTIONS)
94 .overrideOptions(OVERRIDE_OPTIONS)
95 .build();
96 }
97
98
99 @Override
100 public void open() throws CatalogException {
101 this.eventStreamFactory = EventStreamFactory.from(
102 eventSchemasBaseUris,
103 eventStreamConfigUri,
104 httpRoutes
105 );
106 }
107
108 @Override
109 public boolean databaseExists(String databaseName) throws CatalogException {
110
111 return true;
112 }
113
114 @Override
115 public List<String> listTables(String databaseName) throws DatabaseNotExistException, CatalogException {
116 List<String> tables = super.listTables(databaseName);
117 tables.addAll(eventStreamFactory.getEventStreamConfig().cachedStreamNames());
118 return tables;
119 }
120
121 @Override
122 public boolean tableExists(ObjectPath tablePath) {
123 if (eventStreamFactory.getEventStreamConfig().streamExists(tablePath.getObjectName())) {
124 return true;
125 }
126 return super.tableExists(tablePath);
127 }
128
129 @Override
130 public void createTable(ObjectPath tablePath, CatalogBaseTable table, boolean ignoreIfExists)
131 throws TableAlreadyExistException, DatabaseNotExistException, CatalogException {
132 if (eventStreamFactory.getEventStreamConfig().streamExists(tablePath.getObjectName())) {
133 throw new TableAlreadyExistException(this.getName(), tablePath);
134 }
135
136
137 if (table instanceof CatalogView) {
138 super.createTable(tablePath, table, ignoreIfExists);
139 return;
140 }
141
142 List<Schema.UnresolvedColumn> columns = table.getUnresolvedSchema().getColumns();
143
144
145 if (columns.stream().noneMatch(c -> c.getName().equalsIgnoreCase(PLACEHOLDER))) {
146 createTableLike(tablePath, table, ignoreIfExists);
147 } else {
148 createTableOfEventStream(tablePath, table, ignoreIfExists);
149 }
150 }
151
152 private void createTableLike(
153 ObjectPath tablePath,
154 CatalogBaseTable table,
155 boolean ignoreIfExists
156 ) throws TableAlreadyExistException, DatabaseNotExistException {
157 LOG.debug("Creating custom table {}", tablePath.getObjectName());
158
159 Map<String, String> finalTableOptions = this.configurationFactory.
160 createTableLikeEventConfiguration(table.getOptions(), this.eventStreamFactory)
161 .getProcessedOptions();
162 CatalogBaseTable normalizedTable = CatalogTable.of(
163 table.getUnresolvedSchema(),
164 table.getComment(),
165 ((ResolvedCatalogTable) table).getPartitionKeys(),
166 finalTableOptions
167 );
168 super.createTable(tablePath, normalizedTable, ignoreIfExists);
169 }
170
171 private void createTableOfEventStream(
172 ObjectPath tablePath,
173 CatalogBaseTable table,
174 boolean ignoreIfExists
175 ) throws TableAlreadyExistException, DatabaseNotExistException {
176 LOG.debug("Creating table from event stream {}", tablePath.getObjectName());
177
178 EventStreamCatalogConfiguration config = this.configurationFactory.
179 createTableEventConfiguration(table.getOptions(), this.eventStreamFactory);
180 Map<String, String> finalTableOptions = config.getProcessedOptions();
181
182 EventStream eventStream = eventStreamFactory.createEventStream(config.get(STREAM_NAME));
183
184 List<Schema.UnresolvedColumn> incomingColumns = table.getUnresolvedSchema().getColumns().stream().filter(
185 column -> !column.getName().equals(PLACEHOLDER)
186 ).collect(Collectors.toList());
187
188 CatalogBaseTable eventStreamTable;
189 if (config.isKafkaTable()) {
190 eventStreamTable = EventTableUtils.getTableOfEventStream(
191 eventStream,
192 config.get(SCHEMA_VERSION),
193 finalTableOptions,
194 table.getComment(),
195 incomingColumns,
196 config.get(WATERMARK_COLUMN),
197 config.get(WATERMARK_DELAY)
198 );
199 } else {
200 eventStreamTable = EventTableUtils.getTableOfEventStream(
201 eventStream,
202 config.get(SCHEMA_VERSION),
203 finalTableOptions,
204 table.getComment(),
205 incomingColumns
206 );
207 }
208
209 super.createTable(tablePath, eventStreamTable, ignoreIfExists);
210 }
211
212 @Override
213 public CatalogBaseTable getTable(ObjectPath tablePath) throws TableNotExistException {
214 if (super.tableExists(tablePath)) {
215 return super.getTable(tablePath);
216 }
217
218 String streamName = tablePath.getObjectName();
219
220 if (eventStreamFactory.getEventStreamConfig().streamExists(streamName)) {
221 Map<String, String> tableOptions = new HashMap<>();
222 tableOptions.put(STREAM_NAME.key(), streamName);
223 tableOptions.put(SCHEMA_VERSION.key(), eventStreamFactory.createEventStream(streamName).latestSchemaVersion());
224
225 EventStream eventStream = eventStreamFactory.createEventStream(streamName);
226 Configuration config = Configuration.fromMap(this.options);
227
228 return EventTableUtils.getTableOfEventStream(
229 eventStream,
230 eventStream.latestSchemaVersion(),
231 this.configurationFactory
232 .createTableEventConfiguration(tableOptions, this.eventStreamFactory)
233 .getProcessedOptions(),
234 null,
235 null,
236 config.get(WATERMARK_COLUMN),
237 config.get(WATERMARK_DELAY)
238 );
239 }
240
241 throw new TableNotExistException(this.getName(), tablePath);
242 }
243
244 @Override
245 public void dropTable(ObjectPath objectPath, boolean ignoreIfNotExists) throws TableNotExistException, CatalogException {
246 if (super.tableExists(objectPath)) {
247 super.dropTable(objectPath, ignoreIfNotExists);
248 } else if (!ignoreIfNotExists) {
249 if (eventStreamFactory.getEventStreamConfig().streamExists(objectPath.getObjectName())) {
250 throw new CatalogException("Cannot drop an external table. " +
251 "You can only drop tables created with CREATE TABLE");
252 }
253 throw new TableNotExistException(getName(), objectPath);
254 }
255 }
256
257 @SneakyThrows
258 @Override
259 public void alterTable(
260 ObjectPath tablePath,
261 CatalogBaseTable catalogBaseTable,
262 boolean ignoreIfNotExists
263 ) throws TableNotExistException, CatalogException {
264 if (eventStreamFactory.getEventStreamConfig().streamExists(tablePath.getObjectName())) {
265 throw new CatalogException("Cannot alter an external table. " +
266 "You can only alter tables created with CREATE TABLE");
267 }
268
269 if (!super.tableExists(tablePath)) {
270 if (!ignoreIfNotExists) {
271 throw new TableNotExistException(this.getName(), tablePath);
272 }
273 return;
274 }
275
276 Map<String, String> currentTableOptions = catalogBaseTable.getOptions();
277 Map<String, String> cachedTableOptions = super.getTable(tablePath).getOptions();
278 Set<String> immutableOptions = new HashSet<>();
279 immutableOptions.add(STREAM_NAME.key());
280 immutableOptions.add(SCHEMA_VERSION.key());
281
282 MapDifference<String, String> diff = Maps.difference(currentTableOptions, cachedTableOptions);
283 Set<String> changedOptions = new HashSet<>(diff.entriesDiffering().keySet());
284 changedOptions.addAll(diff.entriesOnlyOnLeft().keySet());
285 changedOptions.addAll(diff.entriesOnlyOnRight().keySet());
286
287 LOG.debug("Altered options: {}", diff);
288
289 immutableOptions.forEach(o -> {
290 if (changedOptions.contains(o) ||
291 changedOptions.contains(EventJsonFormatFactory.IDENTIFIER + "." + o)) {
292 throw new CatalogException("Cannot alter option: " + o);
293 }
294 });
295
296 CatalogBaseTable alteredTable = CatalogTable.of(
297 catalogBaseTable.getUnresolvedSchema(),
298 catalogBaseTable.getComment(),
299 ((ResolvedCatalogTable) catalogBaseTable).getPartitionKeys(),
300 this.configurationFactory
301 .createTableEventConfiguration(currentTableOptions, this.eventStreamFactory)
302 .getProcessedOptions()
303 );
304
305 super.alterTable(tablePath, alteredTable, ignoreIfNotExists);
306 }
307
308 }