Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/03.Advanced-Cookbook/3.01.MQTT-Proxy.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,8 @@ Now, we support following filters for MQTTProxy:
- `TopicMapper`: map MQTT Publish packet multi-level topic into single topic and key-value headers.
- `MQTTClientAuth`: provide username and password checking for MQTT Connect packet.
- `KafkaMQTT`: send MQTT Publish message to Kafka backend. By default, `KafkaMQTT` filter will add `clientID`, `username`, `mqttTopic` to Kafka message headers.
If Kafka is unavailable when the filter starts, `KafkaMQTT` keeps retrying producer creation and returns `producerUnavailable` until the producer is ready.
A temporary delivery error appears in the filter's `health` status, which returns to `ready` after Kafka confirms a successful delivery.

## Topic Mapping
In MQTT, there are multi-levels in a topic. Topic mapping is used to map MQTT topic to a single topic with headers. For example:
Expand Down
4 changes: 2 additions & 2 deletions docs/07.Reference/7.02.Filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -1968,7 +1968,7 @@ Rules to revise request header.

| Name | Type | Description | Required |
| ------ | -------- | ------------------------------------------------------------------------------------------------------------ | -------- |
| url | string | Address of the server. The address should start with `http://` or `https://` (when used in the `WebSocketProxy`, it can also start with `ws://` and `wss://`), followed by the hostname or IP address of the server, and then optionally followed by `:{port number}`, for example: `https://www.megaease.com`, `http://10.10.10.10:8080`. When host name is used, the `Host` of a request sent to this server is always the hostname of the server, and therefore using a [RequestAdaptor](#requestadaptor) in the pipeline to modify it will not be possible; when IP address is used, the `Host` is the same as the original request, that can be modified by a [RequestAdaptor](#requestadaptor). See also `KeepHost`. | Yes |
| url | string | Address of the server. The address should start with `http://` or `https://` (when used in the `WebSocketProxy`, it can also start with `ws://` and `wss://`), followed by the hostname or IP address of the server, and then optionally followed by `:{port number}`, for example: `https://www.megaease.cn`, `http://10.10.10.10:8080`. When host name is used, the `Host` of a request sent to this server is always the hostname of the server, and therefore using a [RequestAdaptor](#requestadaptor) in the pipeline to modify it will not be possible; when IP address is used, the `Host` is the same as the original request, that can be modified by a [RequestAdaptor](#requestadaptor). See also `KeepHost`. | Yes |
| tags | []string | Tags of this server, refer `serverTags` in [proxy.PoolSpec](#proxyPoolSpec) | No |
| weight | int | When load balance policy is `weightedRandom`, this value is used to calculate the possibility of this server | No |
| keepHost | bool | If true, the `Host` is the same as the original request, no matter what is the value of `url`. Default value is `false`. | No |
Expand Down Expand Up @@ -2433,4 +2433,4 @@ This configuration is for each object within the `cacheFileExtensionFilters` arr
| Name | Type | Description | Required |
| --- | --- | --- | --- |
| pattern | []string | A list of glob patterns to match files against (e.g., `["*.html", "*.css"]`). | Yes |
| etagMaxAge | integer | The `max-age` value, in seconds, to set for the `ETag` response header for files matching this pattern. Defaults to `3600`. | No |
| etagMaxAge | integer | The `max-age` value, in seconds, to set for the `ETag` response header for files matching this pattern. Defaults to `3600`. | No |
205 changes: 182 additions & 23 deletions pkg/filters/kafka/kafka.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ package kafka

import (
"fmt"
"sync"
"sync/atomic"
"time"

"github.com/Shopify/sarama"
"github.com/megaease/easegress/v2/pkg/context"
Expand All @@ -32,13 +35,14 @@ const (
// Kind is the kind of Kafka
Kind = "KafkaMQTT"

resultGetDataFailed = "getDataFailed"
resultGetDataFailed = "getDataFailed"
resultProducerUnavailable = "producerUnavailable"
)

var kind = &filters.Kind{
Name: Kind,
Description: "Kafka is a kafka proxy for MQTT requests",
Results: []string{resultGetDataFailed},
Results: []string{resultGetDataFailed, resultProducerUnavailable},
DefaultSpec: func() filters.Spec {
return &Spec{}
},
Expand All @@ -54,15 +58,26 @@ func init() {
type (
// Kafka is a kafka proxy for MQTT requests.
Kafka struct {
spec *Spec
producer sarama.AsyncProducer
done chan struct{}
spec *Spec
producer sarama.AsyncProducer
done chan struct{}
closeOnce sync.Once

mu sync.RWMutex
reconnecting int32
lastErr string

defaultTopic string
topicKey string
headerKey string
payloadKey string
}

// Status is the runtime status of Kafka.
Status struct {
Health string `json:"health"`
Ready bool `json:"ready"`
}
)

var _ filters.Filter = (*Kafka)(nil)
Expand Down Expand Up @@ -94,42 +109,151 @@ func (k *Kafka) setKV() {
}
}

var newAsyncProducer = sarama.NewAsyncProducer
var (
newAsyncProducer = sarama.NewAsyncProducer
producerRetryBackoff = time.Second
producerMaxRetryBackoff = 30 * time.Second
)

func (k *Kafka) setProducer() {
func (k *Kafka) setProducer() error {
config := sarama.NewConfig()
config.ClientID = k.spec.Name()
config.Version = sarama.V1_0_0_0
config.Producer.Return.Successes = true
producer, err := newAsyncProducer(k.spec.Backend, config)
if err != nil {
panic(fmt.Errorf("start sarama producer with address %v failed: %v", k.spec.Backend, err))
return fmt.Errorf("start sarama producer with address %v failed: %v", k.spec.Backend, err)
}
k.setReadyProducer(producer)
logger.Infof("kafka mqtt filter %s build sarama producer successfully", k.spec.Name())

go k.watchProducer(producer)
return nil
}

func (k *Kafka) setReadyProducer(producer sarama.AsyncProducer) {
k.mu.Lock()
k.producer = producer
k.lastErr = ""
k.mu.Unlock()
}

func (k *Kafka) clearProducer(producer sarama.AsyncProducer) {
k.mu.Lock()
if k.producer == producer {
k.producer = nil
}
k.mu.Unlock()
}

func (k *Kafka) getProducer() sarama.AsyncProducer {
k.mu.RLock()
defer k.mu.RUnlock()
return k.producer
}

func (k *Kafka) setLastErr(err error) {
k.mu.Lock()
if err == nil {
k.lastErr = ""
} else {
k.lastErr = producerErrString(err)
}
k.mu.Unlock()
}

func producerErrString(err error) string {
if err == nil {
return ""
}
if producerErr, ok := err.(*sarama.ProducerError); ok && producerErr.Err == nil {
return "sarama producer failed"
}
return err.Error()
}

func (k *Kafka) scheduleReconnect() {
if !atomic.CompareAndSwapInt32(&k.reconnecting, 0, 1) {
return
}
retryBackoff := producerRetryBackoff
maxRetryBackoff := producerMaxRetryBackoff

go func() {
defer atomic.StoreInt32(&k.reconnecting, 0)
backoff := retryBackoff
for {
select {
case <-k.done:
err := producer.Close()
if err != nil {
logger.Errorf("close kafka producer failed: %v", err)
}
if !k.waitReconnect(backoff) {
return
case err, ok := <-producer.Errors():
if !ok {
return
}
logger.SpanErrorf(nil, "sarama producer failed: %v", err)
}

err := k.setProducer()
if err == nil {
return
}
k.setLastErr(err)
logger.Errorf("%s kafka producer unavailable: %v", k.spec.Name(), err)
backoff = nextProducerBackoff(backoff, maxRetryBackoff)
}
}()
}

func (k *Kafka) waitReconnect(backoff time.Duration) bool {
timer := time.NewTimer(backoff)
defer timer.Stop()

select {
case <-k.done:
return false
case <-timer.C:
return true
}
}

func nextProducerBackoff(backoff, maxBackoff time.Duration) time.Duration {
backoff *= 2
if backoff > maxBackoff {
return maxBackoff
}
return backoff
}

func (k *Kafka) watchProducer(producer sarama.AsyncProducer) {
successes := producer.Successes()
for {
select {
case <-k.done:
if err := producer.Close(); err != nil {
logger.Errorf("close kafka producer failed: %v", err)
}
return
case _, ok := <-successes:
if !ok {
successes = nil
continue
}
k.setLastErr(nil)
case err, ok := <-producer.Errors():
if !ok {
k.clearProducer(producer)
k.scheduleReconnect()
return
}
k.setLastErr(err)
logger.SpanErrorf(nil, "sarama producer failed: %s", producerErrString(err))
}
}
}

// Init init Kafka
func (k *Kafka) Init() {
k.done = make(chan struct{})
k.setKV()
k.setProducer()
if err := k.setProducer(); err != nil {
k.setLastErr(err)
logger.Errorf("%s kafka producer unavailable: %v", k.spec.Name(), err)
k.scheduleReconnect()
}
}

// Inherit init Kafka based on previous generation
Expand All @@ -139,12 +263,31 @@ func (k *Kafka) Inherit(previousGeneration filters.Filter) {

// Close close Kafka
func (k *Kafka) Close() {
close(k.done)
if k.done == nil {
return
}
k.closeOnce.Do(func() {
close(k.done)
})
}

// Status return status of Kafka
func (k *Kafka) Status() interface{} {
return nil
k.mu.RLock()
defer k.mu.RUnlock()

health := k.lastErr
if health == "" {
health = "initializing"
if k.producer != nil {
health = "ready"
}
}

return &Status{
Health: health,
Ready: k.producer != nil,
}
}

// Handle handles context
Expand Down Expand Up @@ -211,6 +354,22 @@ func (k *Kafka) Handle(ctx *context.Context) string {
Headers: kafkaHeaders,
Value: sarama.ByteEncoder(payload),
}
k.producer.Input() <- msg

producer := k.getProducer()
if producer == nil {
if resp, ok := ctx.GetOutputResponse().(*mqttprot.Response); ok && resp != nil {
resp.SetDrop()
}
return resultProducerUnavailable
}

select {
case producer.Input() <- msg:
case <-k.done:
if resp, ok := ctx.GetOutputResponse().(*mqttprot.Response); ok && resp != nil {
resp.SetDrop()
}
return resultProducerUnavailable
}
return ""
}
Loading
Loading