-
Notifications
You must be signed in to change notification settings - Fork 22
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
15 changed files
with
318 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -37,3 +37,4 @@ build/ | |
__pycache__ | ||
node_modules | ||
.ruby-version | ||
dist |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
#docker build -t otel-analytics:1.0 . | ||
FROM node:21-alpine AS build | ||
|
||
WORKDIR /usr/src/app | ||
|
||
COPY package.json . | ||
|
||
RUN --mount=type=cache,target=/root/.yarn YARN_CACHE_FOLDER=/root/.yarn yarn install --frozen-lockfile --non-interactive --production=true | ||
|
||
COPY src/index.ts src/index.ts | ||
COPY tsconfig.json . | ||
|
||
RUN yarn run build | ||
|
||
FROM node:21-alpine | ||
|
||
WORKDIR /usr/src/app | ||
|
||
COPY package.json . | ||
COPY --from=build /usr/src/app/node_modules node_modules/ | ||
COPY --from=build /usr/src/app/dist/index.js dist/ | ||
|
||
CMD ["yarn", "run", "start"] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"name": "analytics", | ||
"version": "1.0.0", | ||
"main": "src/index.ts", | ||
"scripts": { | ||
"start": "node dist/index.js", | ||
"build": "tsc -p ." | ||
}, | ||
"type": "module", | ||
"license": "Apache License, Version 2.0", | ||
"private": false, | ||
"dependencies": { | ||
"@opentelemetry/api": "^1.6.0", | ||
"@opentelemetry/exporter-trace-otlp-http": "^0.52.0", | ||
"@opentelemetry/resources": "^1.17.0", | ||
"@opentelemetry/sdk-node": "^0.52.0", | ||
"@opentelemetry/sdk-trace-node": "^1.17.0", | ||
"@opentelemetry/semantic-conventions": "^1.17.0", | ||
"mqtt": "^5.1.0", | ||
"ts-node": "^10.9.1" | ||
}, | ||
"devDependencies": { | ||
"typescript": "^5.2.2" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
import {connect} from 'mqtt' | ||
import {NodeSDK} from '@opentelemetry/sdk-node' | ||
import {OTLPTraceExporter} from '@opentelemetry/exporter-trace-otlp-http' | ||
import {context, propagation, trace} from '@opentelemetry/api' | ||
import {Resource} from '@opentelemetry/resources' | ||
import {SEMRESATTRS_SERVICE_NAME} from '@opentelemetry/semantic-conventions' | ||
|
||
function getEnvironmentVariable(name: string): string { | ||
const value = process.env[name] | ||
if (!value) { | ||
throw new Error(`Environment variable ${name} must be defined`) | ||
} | ||
return value | ||
} | ||
|
||
const collectorUri = getEnvironmentVariable('COLLECTOR_URI') | ||
const mqttServerUri = getEnvironmentVariable('MQTT_SERVER_URI') | ||
const clientId = getEnvironmentVariable('MQTT_CLIENT_ID') | ||
const topic = getEnvironmentVariable('MQTT_TOPIC') | ||
const connectTimeout = getEnvironmentVariable('MQTT_CONNECT_TIMEOUT') | ||
|
||
const sdk = new NodeSDK({ | ||
resource: new Resource({[SEMRESATTRS_SERVICE_NAME]: 'analytics'}), | ||
traceExporter: new OTLPTraceExporter({ | ||
url: `${collectorUri}/v1/traces` | ||
}) | ||
}) | ||
|
||
sdk.start() | ||
|
||
const client = connect(mqttServerUri, { | ||
clientId: clientId, protocolVersion: 5, connectTimeout: parseInt(connectTimeout), | ||
}) | ||
|
||
client.on('connect', () => { | ||
console.log('Connected') | ||
client.subscribe([topic], () => { | ||
console.log(`Subscribe to topic '${topic}'`) | ||
}) | ||
}) | ||
|
||
client.on('reconnect', () => { | ||
console.log('Reconnecting') | ||
}) | ||
|
||
client.on('error', (error) => { | ||
console.error(`Cannot connect:`, error) | ||
}) | ||
|
||
client.on('message', (aTopic, payload, packet) => { | ||
if (aTopic === topic) { | ||
|
||
console.log('Received new message') | ||
|
||
const data = JSON.parse(payload.toString()) | ||
|
||
const userProperties: Record<string, any> = {} | ||
if (packet.properties && packet.properties['userProperties']) { | ||
const props = packet.properties['userProperties'] | ||
console.error('Props', props) | ||
for (const key of Object.keys(props)) { | ||
userProperties[key] = props[key] | ||
} | ||
} | ||
|
||
const activeContext = propagation.extract(context.active(), userProperties) | ||
const tracer = trace.getTracer('analytics') | ||
const span = tracer.startSpan( | ||
'Read message', | ||
{attributes: {path: data['path'], clientIp: data['clientIp']}}, | ||
activeContext, | ||
) | ||
span.end() | ||
} | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
{ | ||
"compilerOptions": { | ||
"target": "ES2015", | ||
"module": "nodenext", | ||
"moduleResolution": "nodenext", | ||
"strict": true, | ||
"outDir": "dist", | ||
"rootDir": "src" | ||
}, | ||
"$schema": "https://json.schemastore.org/tsconfig", | ||
"include": ["src/**/*"], | ||
"exclude": ["node_modules"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package ch.frankel.catalog | ||
|
||
import io.opentelemetry.api.OpenTelemetry | ||
import io.opentelemetry.api.trace.SpanContext | ||
import io.opentelemetry.context.Context | ||
import kotlinx.serialization.Serializable | ||
import kotlinx.serialization.encodeToString | ||
import kotlinx.serialization.json.Json | ||
import org.eclipse.paho.mqttv5.client.MqttClient | ||
import org.eclipse.paho.mqttv5.client.MqttConnectionOptions | ||
import org.eclipse.paho.mqttv5.common.MqttMessage | ||
import org.eclipse.paho.mqttv5.common.packet.MqttProperties | ||
import org.eclipse.paho.mqttv5.common.packet.UserProperty | ||
import org.springframework.web.reactive.function.server.HandlerFilterFunction | ||
import org.springframework.web.reactive.function.server.HandlerFunction | ||
import org.springframework.web.reactive.function.server.ServerRequest | ||
import org.springframework.web.reactive.function.server.ServerResponse | ||
import reactor.core.publisher.Mono | ||
import kotlin.jvm.optionals.getOrNull | ||
|
||
|
||
@Serializable | ||
data class Payload(val path: String, val clientIp: String?) | ||
|
||
class MessageHolder(private val req: ServerRequest, private val spanContext: SpanContext, private val options: MessageOptions) { | ||
|
||
val message = MqttMessage().apply { | ||
|
||
properties = MqttProperties().apply { | ||
val traceparent = "00-${spanContext.traceId}-${spanContext.spanId}-${spanContext.traceFlags}" | ||
userProperties = listOf(UserProperty("traceparent", traceparent)) | ||
} | ||
qos = options.qos | ||
isRetained = options.retained | ||
|
||
val hostAddress = req.remoteAddress().map { it.address.hostAddress }.getOrNull() | ||
payload = Json.encodeToString(Payload(req.path(), hostAddress)).toByteArray() | ||
} | ||
} | ||
|
||
class AnalyticsFilter(private val client: MqttClient, private val options: Mqtt, otel: OpenTelemetry) : | ||
HandlerFilterFunction<ServerResponse, ServerResponse> { | ||
|
||
private val tracer = otel.tracerBuilder("ch.frankel.catalog").build() | ||
|
||
override fun filter(req: ServerRequest, next: HandlerFunction<ServerResponse>): Mono<ServerResponse> { | ||
|
||
reconnectIfNeeded() | ||
|
||
val span = tracer.spanBuilder("AnalyticsFilter.filter").setParent(Context.current()).startSpan().apply { | ||
setAttribute("MQTT.topic", options.topic) | ||
setAttribute("MQTT.server-uri", options.serverUri) | ||
setAttribute("MQTT.client-id", options.clientId) | ||
} | ||
val message = MessageHolder(req, span.spanContext, options.message).message | ||
client.publish(options.topic, message) | ||
span.end() | ||
|
||
return next.handle(req) | ||
} | ||
|
||
private fun reconnectIfNeeded() { | ||
if (!client.isConnected) { | ||
val connectionOptions = MqttConnectionOptions().apply { | ||
connectionTimeout = options.connect.timeout | ||
isAutomaticReconnect = options.connect.automatic | ||
} | ||
client.connect(connectionOptions) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
listener 1883 | ||
allow_anonymous true |
Oops, something went wrong.