Debian Codegraph @

server/mqtt_ex_test_test.go

raw
1 // Copyright 2024-2025 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 //go:build !skip_mqtt_tests
15
16 package server
17
18 import (
19 "bytes"
20 "encoding/json"
21 "fmt"
22 "io"
23 "os"
24 "os/exec"
25 "strconv"
26 "strings"
27 "testing"
28
29 "github.com/nats-io/nuid"
30 )
31
32 type mqttDial string
33
34 type mqttTarget struct {
35 singleServers []*Server
36 clusters []*cluster
37 configs []mqttTestConfig
38 all []mqttDial
39 }
40
41 type mqttTestConfig struct {
42 name string
43 pub []mqttDial
44 sub []mqttDial
45 }
46
47 func TestXMQTTCompliance(t *testing.T) {
48 if mqttCLICommandPath == _EMPTY_ {
49 t.Skip(`"mqtt" command is not found in $PATH nor $MQTT_CLI. See https://hivemq.github.io/mqtt-cli/docs/installation/#debian-package for installation instructions`)
50 }
51
52 o := testMQTTDefaultOptions()
53 s := testMQTTRunServer(t, o)
54 o = s.getOpts()
55 defer testMQTTShutdownServer(s)
56
57 cmd := exec.Command(mqttCLICommandPath, "test", "-V", "3", "-p", strconv.Itoa(o.MQTT.Port))
58
59 output, err := cmd.CombinedOutput()
60 t.Log(string(output))
61 if err != nil {
62 if exitError, ok := err.(*exec.ExitError); ok {
63 t.Fatalf("mqtt cli exited with error: %v", exitError)
64 }
65 }
66 }
67
68 func TestXMQTTRetainedMessages(t *testing.T) {
69 if mqttTestCommandPath == _EMPTY_ {
70 t.Skip(`"mqtt-test" command is not found in $PATH.`)
71 }
72
73 for _, topo := range []struct {
74 name string
75 makef func(testing.TB) *mqttTarget
76 }{
77 {
78 name: "single server",
79 makef: mqttMakeTestServer,
80 },
81 {
82 name: "cluster",
83 makef: mqttMakeTestCluster(4, ""),
84 },
85 } {
86 t.Run(topo.name, func(t *testing.T) {
87 target := topo.makef(t)
88 t.Cleanup(target.Shutdown)
89
90 // initialize the MQTT assets by "touching" all nodes in the
91 // cluster, but then reload to start with fresh server state.
92 for _, dial := range target.all {
93 mqttInitTestServer(t, dial)
94 }
95
96 numRMS := 100
97 strNumRMS := strconv.Itoa(numRMS)
98 topics := make([]string, len(target.configs))
99
100 for i, tc := range target.configs {
101 // Publish numRMS retained messages one at a time,
102 // round-robin across pub nodes. Remember the topic for each
103 // test config to check the subs after reload.
104 topic := "subret_" + nuid.Next()
105 topics[i] = topic
106 iNode := 0
107 for i := 0; i < numRMS; i++ {
108 pubTopic := fmt.Sprintf("%s/%d", topic, i)
109 dial := tc.pub[iNode%len(tc.pub)]
110 mqttRunExCommandTest(t, "pub", dial,
111 "--retain",
112 "--topic", pubTopic,
113 "--qos", "0",
114 "--size", "128", // message size 128 bytes
115 )
116 iNode++
117 }
118 }
119
120 // Check all sub nodes for retained messages
121 for i, tc := range target.configs {
122 for _, dial := range tc.sub {
123 mqttRunExCommandTest(t, "sub", dial,
124 "--retained", strNumRMS,
125 "--qos", "0",
126 "--topic", topics[i],
127 )
128 }
129 }
130
131 // Reload the target
132 target.Reload(t)
133
134 // Now check again
135 for i, tc := range target.configs {
136 for _, dial := range tc.sub {
137 mqttRunExCommandTestRetry(t, 1, "sub", dial,
138 "--retained", strNumRMS,
139 "--qos", "0",
140 "--topic", topics[i],
141 )
142 }
143 }
144 })
145 }
146 }
147
148 func mqttInitTestServer(tb testing.TB, dial mqttDial) {
149 tb.Helper()
150 mqttRunExCommandTestRetry(tb, 5, "pub", dial)
151 }
152
153 func mqttNewDialForServer(s *Server, username, password string) mqttDial {
154 o := s.getOpts().MQTT
155 return mqttNewDial(username, password, o.Host, o.Port, s.Name())
156 }
157
158 func mqttNewDial(username, password, host string, port int, comment string) mqttDial {
159 d := ""
160 switch {
161 case username != "" && password != "":
162 d = fmt.Sprintf("%s:%s@%s:%d", username, password, host, port)
163 case username != "":
164 d = fmt.Sprintf("%s@%s:%d", username, host, port)
165 default:
166 d = fmt.Sprintf("%s:%d", host, port)
167 }
168 if comment != "" {
169 d += "#" + comment
170 }
171 return mqttDial(d)
172 }
173
174 func (d mqttDial) Get() (u, p, s, c string) {
175 if d == "" {
176 return "", "", "127.0.0.1:1883", ""
177 }
178 in := string(d)
179 if i := strings.LastIndex(in, "#"); i != -1 {
180 c = in[i+1:]
181 in = in[:i]
182 }
183 if i := strings.LastIndex(in, "@"); i != -1 {
184 up := in[:i]
185 in = in[i+1:]
186 u = up
187 if i := strings.Index(up, ":"); i != -1 {
188 u = up[:i]
189 p = up[i+1:]
190 }
191 }
192 s = in
193 return u, p, s, c
194 }
195
196 func (d mqttDial) Name() string {
197 _, _, _, c := d.Get()
198 return c
199 }
200
201 func (t *mqttTarget) Reload(tb testing.TB) {
202 tb.Helper()
203
204 for _, c := range t.clusters {
205 c.stopAll()
206 c.restartAllSamePorts()
207 }
208
209 for i, s := range t.singleServers {
210 o := s.getOpts()
211 s.Shutdown()
212 t.singleServers[i] = testMQTTRunServer(tb, o)
213 }
214
215 for _, dial := range t.all {
216 mqttInitTestServer(tb, dial)
217 }
218 }
219
220 func (t *mqttTarget) Shutdown() {
221 for _, c := range t.clusters {
222 c.shutdown()
223 }
224 for _, s := range t.singleServers {
225 testMQTTShutdownServer(s)
226 }
227 }
228
229 func mqttMakeTestServer(tb testing.TB) *mqttTarget {
230 tb.Helper()
231 o := testMQTTDefaultOptions()
232 s := testMQTTRunServer(tb, o)
233 all := []mqttDial{mqttNewDialForServer(s, "", "")}
234 return &mqttTarget{
235 singleServers: []*Server{s},
236 all: all,
237 configs: []mqttTestConfig{
238 {
239 name: "single server",
240 pub: all,
241 sub: all,
242 },
243 },
244 }
245 }
246
247 func mqttMakeTestCluster(size int, domain string) func(tb testing.TB) *mqttTarget {
248 return func(tb testing.TB) *mqttTarget {
249 tb.Helper()
250 if size < 3 {
251 tb.Fatal("cluster size must be at least 3")
252 }
253
254 if domain != "" {
255 domain = "domain: " + domain + ", "
256 }
257 clusterConf := `
258 listen: 127.0.0.1:-1
259
260 server_name: %s
261 jetstream: {max_mem_store: 256MB, max_file_store: 2GB, ` + domain + `store_dir: '%s'}
262
263 leafnodes {
264 listen: 127.0.0.1:-1
265 }
266
267 cluster {
268 name: %s
269 listen: 127.0.0.1:%d
270 routes = [%s]
271 }
272
273 mqtt {
274 listen: 127.0.0.1:-1
275 stream_replicas: 3
276 }
277
278 accounts {
279 ONE { users = [ { user: "one", pass: "p" } ]; jetstream: enabled }
280 $SYS { users = [ { user: "admin", pass: "s3cr3t!" } ] }
281 }
282 `
283 cl := createJetStreamClusterWithTemplate(tb, clusterConf, "MQTT", size)
284 cl.waitOnLeader()
285
286 all := []mqttDial{}
287 for _, s := range cl.servers {
288 all = append(all, mqttNewDialForServer(s, "one", "p"))
289 }
290
291 return &mqttTarget{
292 clusters: []*cluster{cl},
293 all: all,
294 configs: []mqttTestConfig{
295 {
296 name: "publish to one",
297 pub: []mqttDial{
298 mqttNewDialForServer(cl.randomServer(), "one", "p"),
299 },
300 sub: all,
301 },
302 {
303 name: "publish to all",
304 pub: all,
305 sub: all,
306 },
307 },
308 }
309 }
310 }
311
312 var mqttCLICommandPath = func() string {
313 p := os.Getenv("MQTT_CLI")
314 if p == "" {
315 p, _ = exec.LookPath("mqtt")
316 }
317 return p
318 }()
319
320 var mqttTestCommandPath = func() string {
321 p, _ := exec.LookPath("mqtt-test")
322 return p
323 }()
324
325 func mqttRunExCommandTest(tb testing.TB, subCommand string, dial mqttDial, extraArgs ...string) *MQTTBenchmarkResult {
326 tb.Helper()
327 return mqttRunExCommandTestRetry(tb, 1, subCommand, dial, extraArgs...)
328 }
329
330 func mqttRunExCommandTestRetry(tb testing.TB, n int, subCommand string, dial mqttDial, extraArgs ...string) (r *MQTTBenchmarkResult) {
331 tb.Helper()
332 var err error
333 for i := 0; i < n; i++ {
334 if r, err = mqttTryExCommandTest(tb, subCommand, dial, extraArgs...); err == nil {
335 return r
336 }
337
338 if i < (n - 1) {
339 tb.Logf("failed to %q %s to %q on attempt %v, will retry.", subCommand, extraArgs, dial.Name(), i)
340 } else {
341 tb.Fatal(err)
342 }
343 }
344 return nil
345 }
346
347 func mqttTryExCommandTest(tb testing.TB, subCommand string, dial mqttDial, extraArgs ...string) (r *MQTTBenchmarkResult, err error) {
348 tb.Helper()
349 if mqttTestCommandPath == "" {
350 tb.Skip(`"mqtt-test" command is not found in $PATH.`)
351 }
352
353 args := []string{subCommand, // "-q",
354 "-s", string(dial),
355 }
356 args = append(args, extraArgs...)
357 cmd := exec.Command(mqttTestCommandPath, args...)
358
359 stdout, err := cmd.StdoutPipe()
360 if err != nil {
361 return nil, fmt.Errorf("error executing %q: %v", cmd.String(), err)
362 }
363 defer stdout.Close()
364 errbuf := bytes.Buffer{}
365 cmd.Stderr = &errbuf
366 if err = cmd.Start(); err != nil {
367 return nil, fmt.Errorf("error executing %q: %v", cmd.String(), err)
368 }
369 out, err := io.ReadAll(stdout)
370 if err != nil {
371 return nil, fmt.Errorf("error executing %q: failed to read output: %v", cmd.String(), err)
372 }
373 if err = cmd.Wait(); err != nil {
374 return nil, fmt.Errorf("error executing %q: %v\n\n%s\n\n%s", cmd.String(), err, string(out), errbuf.String())
375 }
376
377 r = &MQTTBenchmarkResult{}
378 if err := json.Unmarshal(out, r); err != nil {
379 tb.Fatalf("error executing %q: failed to decode output: %v\n\n%s\n\n%s", cmd.String(), err, string(out), errbuf.String())
380 }
381 return r, nil
382 }