1
1
package kafka
2
2
3
3
import (
4
+ "crypto/tls"
5
+ "crypto/x509"
4
6
"errors"
5
7
"fmt"
6
-
7
8
"github.com/Shopify/sarama"
8
9
"github.com/influxdb/influxdb/client/v2"
9
10
"github.com/influxdb/telegraf/plugins/outputs"
11
+ "io/ioutil"
10
12
)
11
13
12
14
type Kafka struct {
@@ -16,8 +18,17 @@ type Kafka struct {
16
18
Topic string
17
19
// Routing Key Tag
18
20
RoutingTag string `toml:"routing_tag"`
21
+ // TLS client certificate
22
+ Certificate string
23
+ // TLS client key
24
+ Key string
25
+ // TLS certificate authority
26
+ CA string
27
+ // Verfiy SSL certificate chain
28
+ VerifySsl bool
19
29
20
- producer sarama.SyncProducer
30
+ tlsConfig tls.Config
31
+ producer sarama.SyncProducer
21
32
}
22
33
23
34
var sampleConfig = `
@@ -28,10 +39,60 @@ var sampleConfig = `
28
39
# Telegraf tag to use as a routing key
29
40
# ie, if this tag exists, it's value will be used as the routing key
30
41
routing_tag = "host"
42
+
43
+ # Optional TLS configuration:
44
+ # Client certificate
45
+ certificate = ""
46
+ # Client key
47
+ key = ""
48
+ # Certificate authority file
49
+ ca = ""
50
+ # Verify SSL certificate chain
51
+ verify_ssl = false
31
52
`
32
53
54
+ func createTlsConfiguration (k * Kafka ) (t * tls.Config , err error ) {
55
+ if k .Certificate != "" && k .Key != "" && k .CA != "" {
56
+ cert , err := tls .LoadX509KeyPair (k .Certificate , k .Key )
57
+ if err != nil {
58
+ return nil , errors .New (fmt .Sprintf ("Cout not load Kafka TLS client key/certificate: %s" ,
59
+ err ))
60
+ }
61
+
62
+ caCert , err := ioutil .ReadFile (k .CA )
63
+ if err != nil {
64
+ return nil , errors .New (fmt .Sprintf ("Cout not load Kafka TLS CA: %s" ,
65
+ err ))
66
+ }
67
+
68
+ caCertPool := x509 .NewCertPool ()
69
+ caCertPool .AppendCertsFromPEM (caCert )
70
+
71
+ t = & tls.Config {
72
+ Certificates : []tls.Certificate {cert },
73
+ RootCAs : caCertPool ,
74
+ InsecureSkipVerify : k .VerifySsl ,
75
+ }
76
+ }
77
+ // will be nil by default if nothing is provided
78
+ return t , nil
79
+ }
80
+
33
81
func (k * Kafka ) Connect () error {
34
- producer , err := sarama .NewSyncProducer (k .Brokers , nil )
82
+ config := sarama .NewConfig ()
83
+ config .Producer .RequiredAcks = sarama .WaitForAll // Wait for all in-sync replicas to ack the message
84
+ config .Producer .Retry .Max = 10 // Retry up to 10 times to produce the message
85
+ tlsConfig , err := createTlsConfiguration (k )
86
+ if err != nil {
87
+ return err
88
+ }
89
+
90
+ if tlsConfig != nil {
91
+ config .Net .TLS .Config = tlsConfig
92
+ config .Net .TLS .Enable = true
93
+ }
94
+
95
+ producer , err := sarama .NewSyncProducer (k .Brokers , config )
35
96
if err != nil {
36
97
return err
37
98
}
0 commit comments