-
Notifications
You must be signed in to change notification settings - Fork 38
/
main.go
236 lines (211 loc) · 6.36 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
// Copyright 2018 Comcast Cable Communications Management, LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// This program offers a simple CLI utility for interacting
// with a Pulsar server using the `pulsar` package.
//
// It's main goal is to aid in testing and debugging of the `pulsar`
// package.
package main
import (
"bufio"
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"os"
"os/signal"
"syscall"
"time"
"github.com/Comcast/pulsar-client-go"
)
var args = struct {
pulsar string
tlsCert string
tlsKey string
tlsCA string
tlsSkipVerify bool
name string
topic string
producer bool
message string
messageRate time.Duration
shared bool
}{
pulsar: "localhost:6650",
tlsCert: "",
tlsKey: "",
tlsCA: "",
tlsSkipVerify: false,
name: "demo",
topic: "persistent://sample/standalone/ns1/demo",
producer: false,
message: "--",
messageRate: time.Second,
shared: false,
}
func main() {
flag.StringVar(&args.pulsar, "pulsar", args.pulsar, "pulsar address")
flag.StringVar(&args.tlsCert, "tls-cert", args.tlsCert, "(optional) path to TLS certificate")
flag.StringVar(&args.tlsKey, "tls-key", args.tlsKey, "(optional) path to TLS key")
flag.StringVar(&args.tlsCA, "tls-ca", args.tlsKey, "(optional) path to root certificate")
flag.BoolVar(&args.tlsSkipVerify, "tls-insecure", args.tlsSkipVerify, "if true, do not verify server certificate chain when using TLS")
flag.StringVar(&args.name, "name", args.name, "producer/consumer name")
flag.StringVar(&args.topic, "topic", args.topic, "producer/consumer topic")
flag.BoolVar(&args.producer, "producer", args.producer, "if true, produce messages, otherwise consume")
flag.StringVar(&args.message, "message", args.message, "If equal to '--', then STDIN will be used. Otherwise value with %03d $messageNumber tacked on the front will be sent")
flag.DurationVar(&args.messageRate, "rate", args.messageRate, "rate at which to send messages")
flag.BoolVar(&args.shared, "shared", args.shared, "if true, consumer is shared, otherwise exclusive")
flag.Parse()
asyncErrs := make(chan error, 8)
go func() {
for err := range asyncErrs {
fmt.Fprintln(os.Stderr, "error:", err)
}
}()
ctx, cancel := context.WithCancel(context.Background())
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
cancel()
}()
var tlsCfg *tls.Config
if args.tlsCert != "" && args.tlsKey != "" {
tlsCfg = &tls.Config{
InsecureSkipVerify: args.tlsSkipVerify,
}
var err error
cert, err := tls.LoadX509KeyPair(args.tlsCert, args.tlsKey)
if err != nil {
fmt.Fprintln(os.Stderr, "error loading certificates:", err)
os.Exit(1)
}
tlsCfg.Certificates = []tls.Certificate{cert}
if args.tlsCA != "" {
rootCA, err := ioutil.ReadFile(args.tlsCA)
if err != nil {
fmt.Fprintln(os.Stderr, "error loading certificate authority:", err)
os.Exit(1)
}
tlsCfg.RootCAs = x509.NewCertPool()
tlsCfg.RootCAs.AppendCertsFromPEM(rootCA)
}
// Inspect certificate and print the CommonName attribute,
// since this may be used for authorization
if len(cert.Certificate[0]) > 0 {
x509Cert, err := x509.ParseCertificate(cert.Certificate[0])
if err != nil {
fmt.Fprintln(os.Stderr, "error loading public certificate:", err)
os.Exit(1)
}
fmt.Printf("Using certificate pair with CommonName = %q\n", x509Cert.Subject.CommonName)
}
}
mcp := pulsar.NewManagedClientPool()
switch args.producer {
case true:
// Create the managed producer
mpCfg := pulsar.ManagedProducerConfig{
Name: args.name,
Topic: args.topic,
NewProducerTimeout: time.Second,
InitialReconnectDelay: time.Second,
MaxReconnectDelay: time.Minute,
ManagedClientConfig: pulsar.ManagedClientConfig{
ClientConfig: pulsar.ClientConfig{
Addr: args.pulsar,
TLSConfig: tlsCfg,
Errs: asyncErrs,
},
},
}
mp := pulsar.NewManagedProducer(mcp, mpCfg)
fmt.Printf("Created producer on topic %q...\n", args.topic)
// messages to produce are sent to this
// channel
messages := make(chan []byte)
switch args.message {
// read messages from STDIN
case "--":
go func() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Bytes()
cp := make([]byte, len(line))
copy(cp, line)
messages <- cp
}
close(messages)
}()
default:
go func() {
var i int
for range time.NewTicker(args.messageRate).C {
i++
messages <- []byte(fmt.Sprintf("%03d %s", i, args.message))
}
}()
}
for {
select {
case payload, ok := <-messages:
if !ok {
return
}
sctx, cancel := context.WithTimeout(ctx, time.Second)
_, err := mp.Send(sctx, payload)
cancel()
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
case <-ctx.Done():
return
}
}
case false:
queue := make(chan pulsar.Message, 8)
// Create managed consumer
mcCfg := pulsar.ManagedConsumerConfig{
Name: args.name,
Topic: args.topic,
Exclusive: !args.shared,
NewConsumerTimeout: time.Second,
InitialReconnectDelay: time.Second,
MaxReconnectDelay: time.Minute,
ManagedClientConfig: pulsar.ManagedClientConfig{
ClientConfig: pulsar.ClientConfig{
Addr: args.pulsar,
TLSConfig: tlsCfg,
Errs: asyncErrs,
},
},
}
mc := pulsar.NewManagedConsumer(mcp, mcCfg)
go mc.ReceiveAsync(ctx, queue)
fmt.Printf("Created consumer %q on topic %q...\n", args.name, args.topic)
for {
select {
case <-ctx.Done():
return
case msg := <-queue:
fmt.Println(string(msg.Payload))
if err := mc.Ack(ctx, msg); err != nil {
fmt.Fprintf(os.Stderr, "error acking message: %v", err)
}
}
}
}
}