KafkaTopology.kt 15.6 KB
Newer Older
Jonas Waeber's avatar
Jonas Waeber committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 * fedora-metadata-extractor
 * Copyright (C) 2020 Memoriav
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package org.memobase

21
22
23
24
25
26
import ch.memobase.rdf.FEDORA
import ch.memobase.rdf.LDP
import ch.memobase.rdf.MB
import ch.memobase.rdf.RDF
import ch.memobase.rdf.RICO
import ch.memobase.settings.SettingsLoader
27
28
import com.fasterxml.jackson.core.JsonParseException
import com.fasterxml.jackson.databind.JsonMappingException
Jonas Waeber's avatar
Jonas Waeber committed
29
import com.fasterxml.jackson.databind.ObjectMapper
30
31
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.databind.util.StdDateFormat
Jonas Waeber's avatar
Jonas Waeber committed
32
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
33
34
35
36
37
38
39
40
41
42
import java.net.URI
import java.nio.charset.StandardCharsets
import java.time.Duration
import java.util.Properties
import kotlin.collections.HashMap
import org.apache.jena.rdf.model.Model
import org.apache.jena.rdf.model.ModelFactory
import org.apache.jena.rdf.model.Property
import org.apache.jena.rdf.model.Resource
import org.apache.jena.rdf.model.ResourceFactory
Jonas Waeber's avatar
Jonas Waeber committed
43
import org.apache.jena.rdf.model.impl.SelectorImpl
Jonas Waeber's avatar
Jonas Waeber committed
44
45
import org.apache.jena.riot.Lang
import org.apache.jena.riot.RDFDataMgr
Matthias's avatar
Matthias committed
46
47
48
49
import org.apache.kafka.clients.consumer.Consumer
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.Producer
50
import org.apache.kafka.clients.producer.ProducerRecord
Matthias's avatar
Matthias committed
51
52
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.kafka.common.serialization.StringSerializer
53
import org.apache.kafka.streams.Topology
Jonas Waeber's avatar
Jonas Waeber committed
54
import org.apache.logging.log4j.LogManager
55
import org.fcrepo.client.FcrepoOperationFailedException
Jonas Waeber's avatar
Jonas Waeber committed
56
import org.memobase.fedora.FedoraClientImpl
Jonas Waeber's avatar
Jonas Waeber committed
57
import org.memobase.fedora.RdfResponseTypes
Jonas Waeber's avatar
Jonas Waeber committed
58
59
60
61
62
63
64
65
66
import org.memobase.model.EventMessage

class KafkaTopology(
    private val settings: SettingsLoader
) {
    private val log = LogManager.getLogger("FedoraMetadataExtractor")

    private val objectMapper = ObjectMapper().registerKotlinModule()
    private val fedora = FedoraClientImpl.builder()
Jonas Waeber's avatar
Jonas Waeber committed
67
        .properties(settings.appSettings, "fedora")
Jonas Waeber's avatar
Jonas Waeber committed
68
69
        .build()

Matthias's avatar
Matthias committed
70
71
72
73
74
75
    fun run(): Topology {
        val jsonMapper = ObjectMapper().apply {
            registerKotlinModule()
            disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            setDateFormat(StdDateFormat())
        }
Jonas Waeber's avatar
Jonas Waeber committed
76

Matthias's avatar
Matthias committed
77
78
79
80
81
82
83
84
85
        lateinit var consumer: Consumer<String, String>
        lateinit var producer: Producer<String, String>
        try {
            consumer = createConsumer()
            producer = createProducer()
            consumer.subscribe(listOf(settings.inputTopic))
        } catch (ex: Exception) {
            log.error("Exception during ceating kafka consumer/producer: " + ex.toString())
        }
Jonas Waeber's avatar
Jonas Waeber committed
86

Matthias's avatar
Matthias committed
87
88
89
90
91
92
93
94
        while (true) {
            try {
                val records = consumer.poll(Duration.ofSeconds(1))
                records.iterator().forEach {
                    var eventJson = it.value()
                    var event = jsonMapper.readValue(eventJson, org.memobase.model.EventMessage::class.java)
                    var eventRdf: List<Pair<EventMessage, String>> = requestPrimaryResource(event)
                    var eventModel: Pair<EventMessage, Model> = parseModel(eventRdf[0])
95
96
                    val valueWithHeader: Triple<EventMessage, Model, HashMap<String, String>> =
                        extractHeaderMetadata(eventModel)
Matthias's avatar
Matthias committed
97
98
99
100
101
102
103
                    val headerData: HashMap<String, String> = valueWithHeader.third
                    var model: Model = addEventType(eventModel)
                    if (headerData["objectType"] == "rico:Record") {
                        model = requestAdditionalRecordResources(model)
                    }
                    model = filterFedoraProperties(model)
                    val modelString: String = Functions.writeModel(model)
Jonas Waeber's avatar
Jonas Waeber committed
104

Matthias's avatar
Matthias committed
105
106
                    var outputTopic = settings.outputTopic + when (event.objectType) {
                        "rico:Record" -> "-json-records"
Matthias's avatar
Matthias committed
107
                        "rico:VersionedRecord" -> "-json-records"
Matthias's avatar
Matthias committed
108
109
110
111
112
113
                        "rico:RecordSet" -> "-json-record-sets"
                        "rico:CorporateBody" -> "-json-institutions"
                        else -> "-XXX"
                    }

                    var producerRecord: ProducerRecord<String, String> =
114
                        ProducerRecord(outputTopic, it.key(), modelString)
115
116
117
118
119
120
121
122
123
124
125
126
127
                    if (headerData.containsKey("institutionId")) {
                        producerRecord.headers().add("institutionId", headerData["institutionId"]?.toByteArray())
                    }
                    if (headerData.containsKey("recordSetId")) {
                        producerRecord.headers().add("recordSetId", headerData["recordSetId"]?.toByteArray())
                    }
                    if (headerData.containsKey("recordId")) {
                        producerRecord.headers().add("recordId", headerData["recordId"]?.toByteArray())
                    }

                    if (headerData.containsKey("isPublished")) {
                        producerRecord.headers().add("isPublished", headerData["isPublished"]?.toByteArray())
                    }
Matthias's avatar
Matthias committed
128
129

                    producer.send(producerRecord)
130
131
132
133
                    log.debug(
                        "FedoraEvent " + event.eventId +
                                " written to topic '" + outputTopic + "'."
                    )
Matthias's avatar
Matthias committed
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
                }
            } catch (ex: Exception) {
                log.error("Exception during processing eventMessages: " + ex.toString())
            }
        }
    }

    private fun extractHeaderMetadata(value: Pair<EventMessage, Model>): Triple<EventMessage, Model, HashMap<String, String>> {
        val eventMsg = value.first
        val rdfModel = value.second
        var headerData: HashMap<String, String> = HashMap<String, String>()
        try {
            val subjectUri = eventMsg.objectPath
            var isPublishedProp = MB.isPublished // TODO: use MB.isPublished as soon as http VS https is unified
            isPublishedProp = ResourceFactory.createProperty("http://memobase.ch/internal/", "isPublished")
            if (eventMsg.objectType == "rico:Record") {
                headerData.put(
                    "recordId",
                    eventMsg.objectPath.substring(subjectUri.lastIndexOf('/') + 1)
                )
                val recordSetId = getPropertyAsString(subjectUri, rdfModel, RICO.isPartOf)
                headerData.put(
                    "recordSetId",
                    recordSetId.substring(recordSetId.lastIndexOf('/') + 1)
                )
                val institutionId = getPropertyAsString(subjectUri, rdfModel, RICO.heldBy)
                headerData.put(
                    "institutionId",
                    institutionId.substring(institutionId.lastIndexOf('/') + 1)
                )
                val isPublished = getPropertyAsString(subjectUri, rdfModel, isPublishedProp)
                headerData.put("isPublished", isPublished)
            } else if (eventMsg.objectType == "rico:RecordSet") {
                headerData.put(
                    "recordsetId",
                    eventMsg.objectPath.substring(subjectUri.lastIndexOf('/') + 1)
                )
                val institutionId = getPropertyAsString(subjectUri, rdfModel, RICO.heldBy)
                headerData.put(
                    "institutionId",
                    institutionId.substring(institutionId.lastIndexOf('/') + 1)
                )
                val isPublished = getPropertyAsString(subjectUri, rdfModel, isPublishedProp)
                headerData.put("isPublished", isPublished)
            } else if (eventMsg.objectType == "rico:Institution") {
                headerData.put(
                    "institutionId",
                    eventMsg.objectPath.substring(subjectUri.lastIndexOf('/') + 1)
                )
                val recordSetIds = getPropertyAsString(subjectUri, rdfModel, RICO.isHolderOf)
                headerData.put(
                    "recordsetIds",
                    recordSetIds.substring(eventMsg.objectPath.lastIndexOf('/') + 1)
                )
                val isPublished = getPropertyAsString(subjectUri, rdfModel, isPublishedProp)
                headerData.put("isPublished", isPublished)
            }
        } catch (ex: Exception) {
            log.error("Exception while extracting HeaderData for " + eventMsg.eventId + ": " + ex.message)
        }
        return Triple(eventMsg, rdfModel, headerData)
    }

    private fun getResourceFromRdf(model: Model, uri: String): Resource {
        return model.getResource(uri)
    }

    private fun getPropertyAsString(subjectUri: String, model: Model, property: Property): String {
        val subject = model.getResource(subjectUri)
        val objects = subject.listProperties(property).mapWith {
204
205
206
207
208
209
210
            val o = it.`object`
            when {
                o.isURIResource -> o.asResource().uri
                o.isLiteral -> o.asLiteral().value.toString()
                else -> o.toString()
            }
        }.toList()
Matthias's avatar
Matthias committed
211
        return when {
212
213
            objects.size <= 0 -> throw Exception("No property $property found.")
            objects.size > 1 -> throw Exception("More than 1 property $property found")
Matthias's avatar
Matthias committed
214
215
            else -> objects[0]
        }
Jonas Waeber's avatar
Jonas Waeber committed
216
217
    }

218
219
220
221
222
223
224
225
226
227
    private fun parseMessage(data: String): List<EventMessage> {
        return try {
            listOf(objectMapper.readValue(data, EventMessage::class.java))
        } catch (ex: JsonParseException) {
            log.error("Invalid json found: $data")
            emptyList()
        } catch (ex: JsonMappingException) {
            log.error("Could not parse the json object as an event message: $data")
            emptyList()
        }
Jonas Waeber's avatar
Jonas Waeber committed
228
229
    }

230
231
    private fun requestPrimaryResource(message: EventMessage): List<Pair<EventMessage, String>> {
        return try {
232
233
234
235
236
237
            listOf(
                Pair(
                    message,
                    fedora.fetchRdfResourceIntoString(URI.create(message.objectPath), RdfResponseTypes.NTRIPLES)
                )
            )
238
239
240
241
242
243
244
245
        } catch (ex: FcrepoOperationFailedException) {
            when (ex.statusCode) {
                410 -> log.error("Status: ${ex.statusCode} -> The resource at path ${message.objectPath} has been deleted.")
                404 -> log.error("Status: ${ex.statusCode} -> No resource found at path ${message.objectPath}.")
                else -> log.error("Status: ${ex.statusCode} -> Unknown Error: ${ex.localizedMessage}.")
            }
            emptyList()
        }
Jonas Waeber's avatar
Jonas Waeber committed
246
247
248
249
250
251
252
253
254
    }

    private fun parseModel(input: Pair<EventMessage, String>): Pair<EventMessage, Model> {
        val model = ModelFactory.createDefaultModel()
        RDFDataMgr.read(model, input.second.byteInputStream(StandardCharsets.UTF_8), Lang.NT)
        return Pair(input.first, model)
    }

    /**
Jonas Waeber's avatar
Jonas Waeber committed
255
256
     *  Adds the type of the event message to the core resources.
     *  Core resources are rico:Record, rico:CorporateBody (for institutions), rico:RecordSet and rico:Instantiations.
Jonas Waeber's avatar
Jonas Waeber committed
257
258
     *  Downstream services should remove this property before publishing the data to the outside world!
     */
Jonas Waeber's avatar
Jonas Waeber committed
259
    private fun addEventType(input: Pair<EventMessage, Model>): Model {
Jonas Waeber's avatar
Jonas Waeber committed
260
        // TODO: Add filter for corporate body so that only memobase institutions are flagged.
Jonas Waeber's avatar
Jonas Waeber committed
261
        listOf(RICO.Record, RICO.CorporateBody, RICO.RecordSet, RICO.Instantiation).forEach {
Jonas Waeber's avatar
Jonas Waeber committed
262
263
            val record = input.second.listSubjectsWithProperty(RDF.type, it).toList()
            if (record.isNotEmpty()) {
Jonas Waeber's avatar
Jonas Waeber committed
264
                record[0].addProperty(MB.eventType, input.first.eventType)
Jonas Waeber's avatar
Jonas Waeber committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
            }
        }
        return input.second
    }

    private fun requestAdditionalRecordResources(model: Model): Model {
        val subjects = model.listSubjectsWithProperty(RDF.type, RICO.Record).toList()
        if (subjects.isEmpty()) {
            // TODO: Improve exception handling
            throw Exception("The requested resource is not a record...")
        } else {
            val subject = subjects[0]!!
            requestAdditionalResources(subject, model, RICO.heldBy)
            requestAdditionalResources(subject, model, RICO.isPartOf)
            requestAdditionalResources(subject, model, RICO.hasInstantiation)
        }
        return model
    }

    private fun requestAdditionalResources(subject: Resource, model: Model, property: Property) {
        if (subject.hasProperty(property)) {
            subject.listProperties(property).forEach {
                if (it.`object`.isResource) {
                    val uri = it.`object`.asResource().uri
Jonas Waeber's avatar
Jonas Waeber committed
289
                    val data = fedora.fetchRdfResourceIntoString(URI(uri), RdfResponseTypes.NTRIPLES)
Jonas Waeber's avatar
Jonas Waeber committed
290
291
292
293
294
295
                    RDFDataMgr.read(model, data.byteInputStream(StandardCharsets.UTF_8), Lang.NT)
                }
            }
        }
    }

Jonas Waeber's avatar
Jonas Waeber committed
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
    private fun filterFedoraProperties(model: Model): Model {
        // This value is required for the compiler to be able to use the SelectorImpl constructor
        val typedValue: String? = null

        listOf(
            FEDORA.created,
            FEDORA.createdBy,
            FEDORA.lastModified,
            FEDORA.lastModifiedBy
        ).forEach {
            val createdStatements = model.listStatements(
                SelectorImpl(null, it, typedValue)
            )
            model.remove(createdStatements)
        }

        listOf(
            LDP.Container,
            LDP.BasicContainer,
            LDP.RDFSource,
            FEDORA.Container,
            FEDORA.Resource
        ).forEach {
            val createdStatements = model.listStatements(
                SelectorImpl(null, RDF.type, it)
            )
            model.remove(createdStatements)
        }
        return model
    }
Matthias's avatar
Matthias committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355

    private fun createConsumer(): Consumer<String, String> {
        val props = Properties()
        props["bootstrap.servers"] = listOf(settings.kafkaConsumerSettings)[0]["bootstrap.servers"].toString()
        props["group.id"] = listOf(settings.kafkaConsumerSettings)[0]["group.id"].toString()
        props["client.id"] = listOf(settings.kafkaConsumerSettings)[0]["client.id"].toString()
        props["key.deserializer"] = StringDeserializer::class.java
        props["value.deserializer"] = StringDeserializer::class.java
        props["enable.auto.commit"] = false
        props["max.poll.records"] = "10"
        props["max.poll.interval.ms"] = "3600000"
        props["max.poll.interval.ms"] = "3600000"
        props["auto.offset.reset"] = "earliest"
        props["allow.auto.create.topics"] = false
        lateinit var consumer: org.apache.kafka.clients.consumer.KafkaConsumer<String, String>
        try {
            consumer = KafkaConsumer<String, String>(props)
        } catch (t: Exception) {
            consumer = KafkaConsumer<String, String>(props)
        }
        return consumer
    }

    private fun createProducer(): Producer<String, String> {
        val props = Properties()
        props["bootstrap.servers"] = listOf(settings.kafkaProducerSettings)[0]["bootstrap.servers"].toString()
        props["key.serializer"] = StringSerializer::class.java
        props["value.serializer"] = StringSerializer::class.java
        return KafkaProducer<String, String>(props)
    }
Jonas Waeber's avatar
Jonas Waeber committed
356
}