2 // Copyright © 2016 Guy M. Alluard
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
8 // http://www.apache.org/licenses/LICENSE-2.0
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
18 Package sngecomm provides common functionality used in the stompngo_examples
32 "github.com/gmallard/stompngo"
33 "github.com/gmallard/stompngo/senv"
37 llu
= log
.New(os
.Stdout
, "UTIL ", log
.Ldate|log
.Lmicroseconds|log
.Lshortfile
)
41 // Provide connect headers
42 func ConnectHeaders() stompngo
.Headers
{
43 h
:= stompngo
.Headers
{}
50 h
= h
.Add("passcode", pc
)
54 if p
!= stompngo
.SPL_10
{ // 1.1 and 1.2
55 h
= h
.Add("accept-version", p
).Add("host", senv
.Vhost())
58 hb
:= senv
.Heartbeats()
60 h
= h
.Add("heart-beat", hb
)
66 // Show connection metrics.
67 func ShowStats(exampid
, tag
string, conn
*stompngo
.Connection
) {
68 r
:= conn
.FramesRead()
69 br
:= conn
.BytesRead()
70 w
:= conn
.FramesWritten()
71 bw
:= conn
.BytesWritten()
72 s
:= conn
.Running().Seconds()
73 n
:= conn
.Running().Nanoseconds()
74 llu
.Printf("%stag:%s frame_read_count:%v\n", exampid
, tag
, r
)
75 llu
.Printf("%stag:%s bytes_read:%v\n", exampid
, tag
, br
)
76 llu
.Printf("%stag:%s frame_write_count:%v\n", exampid
, tag
, w
)
77 llu
.Printf("%stag:%s bytes_written:%v\n", exampid
, tag
, bw
)
78 llu
.Printf("%stag:%s current_duration(ns):%v\n", exampid
, tag
, n
)
80 llu
.Printf("%stag:%s current_duration(sec):%20.6f\n", exampid
, tag
, s
)
81 llu
.Printf("%stag:%s frame_reads/sec:%20.6f\n", exampid
, tag
, float64(r
)/s
)
82 llu
.Printf("%stag:%s bytes_read/sec:%20.6f\n", exampid
, tag
, float64(br
)/s
)
83 llu
.Printf("%stag:%s frame_writes/sec:%20.6f\n", exampid
, tag
, float64(w
)/s
)
84 llu
.Printf("%stag:%s bytes_written/sec:%20.6f\n", exampid
, tag
, float64(bw
)/s
)
87 // Get a value between min amd max
88 func ValueBetween(min
, max
int64, fact
float64) int64 {
89 rt
, _
:= rand
.Int(rand
.Reader
, big
.NewInt(max
-min
)) // Ignore errors here
90 return int64(fact
* float64(min
+rt
.Int64()))
93 // Dump a TLS Configuration Struct
94 func DumpTLSConfig(exampid
string, c
*tls
.Config
, n
*tls
.Conn
) {
95 llu
.Printf("%s TLSConfig:\n", exampid
)
96 llu
.Printf("%s Rand:%v\n", exampid
, c
.Rand
)
97 llu
.Printf("%s Time:%v\n", exampid
, c
.Time
)
98 llu
.Printf("%s Certificates:%v\n", exampid
, c
.Certificates
)
99 llu
.Printf("%s NameToCertificate:%v\n", exampid
, c
.NameToCertificate
)
100 llu
.Printf("%s RootCAs:%v\n", exampid
, c
.RootCAs
)
101 llu
.Printf("%s NextProtos:%v\n", exampid
, c
.NextProtos
)
102 llu
.Printf("%s ServerName:%v\n", exampid
, c
.ServerName
)
103 llu
.Printf("%s ClientAuth:%v\n", exampid
, c
.ClientAuth
)
104 llu
.Printf("%s ClientCAs:%v\n", exampid
, c
.ClientCAs
)
105 llu
.Printf("%s CipherSuites:%v\n", exampid
, c
.CipherSuites
)
106 llu
.Printf("%s PreferServerCipherSuites:%v\n", exampid
, c
.PreferServerCipherSuites
)
107 llu
.Printf("%s SessionTicketsDisabled:%v\n", exampid
, c
.SessionTicketsDisabled
)
108 llu
.Printf("%s SessionTicketKey:%v\n", exampid
, c
.SessionTicketKey
)
110 // Idea Embelluished From:
111 // https://groups.google.com/forum/#!topic/golang-nuts/TMNdOxugbTY
112 cs
:= n
.ConnectionState()
113 llu
.Printf("%s HandshakeComplete:%v\n", exampid
, cs
.HandshakeComplete
)
114 llu
.Printf("%s DidResume:%v\n", exampid
, cs
.DidResume
)
115 llu
.Printf("%s CipherSuite:%d(0x%X)\n", exampid
, cs
.CipherSuite
, cs
.CipherSuite
)
116 llu
.Printf("%s NegotiatedProtocol:%v\n", exampid
, cs
.NegotiatedProtocol
)
117 llu
.Printf("%s NegotiatedProtocolIsMutual:%v\n", exampid
, cs
.NegotiatedProtocolIsMutual
)
118 // llu.Printf("%s ServerName:%v\n", exampid, cs.ServerName) // Server side only
119 // Portions of any Peer Certificates present
120 certs
:= cs
.PeerCertificates
121 if certs
== nil ||
len(certs
) < 1 {
122 llu
.Printf("Could not get server's certificate from the TLS connection.\n")
125 llu
.Printf("%s Server Certs:\n", exampid
)
126 for i
, cert
:= range certs
{
127 llu
.Printf("%s Certificate chain:%d\n", exampid
, i
)
128 llu
.Printf("%s Common Name:%s\n", exampid
, cert
.Subject
.CommonName
)
130 llu
.Printf("%s Subject Alternative Names (DNSNames):\n", exampid
)
131 for idx
, dnsn
:= range cert
.DNSNames
{
132 llu
.Printf("%s \tNumber:%d, DNS Name:%s\n", exampid
, idx
+1, dnsn
)
135 llu
.Printf("%s Subject Alternative Names (Emailaddresses):\n", exampid
)
136 for idx
, enn
:= range cert
.EmailAddresses
{
137 llu
.Printf("%s \tNumber:%d, DNS Name:%s\n", exampid
, idx
+1, enn
)
140 llu
.Printf("%s Subject Alternative Names (IPAddresses):\n", exampid
)
141 for idx
, ipadn
:= range cert
.IPAddresses
{
142 llu
.Printf("%s \tNumber:%d, DNS Name:%v\n", exampid
, idx
+1, ipadn
)
145 llu
.Printf("%s Valid Not Before:%s\n", exampid
, cert
.NotBefore
.Local().String())
146 llu
.Printf("%s Valid Not After:%s\n", exampid
, cert
.NotAfter
.Local().String())
147 llu
.Println(strings
.Repeat("=", 80))
152 // Handle a subscribe for the different protocol levels.
153 func HandleSubscribe(c
*stompngo
.Connection
, d
, i
, a
string) <-chan stompngo
.MessageData
{
154 h
:= stompngo
.Headers
{"destination", d
, "ack", a
}
156 switch c
.Protocol() {
157 case stompngo
.SPL_12
:
158 // Add required id header
160 case stompngo
.SPL_11
:
161 // Add required id header
163 case stompngo
.SPL_10
:
164 // Nothing else to do here
166 llu
.Fatalf("v1:%v v2:%v\n", "subscribe invalid protocol level, should not happen")
169 r
, e
:= c
.Subscribe(h
)
171 llu
.Fatalf("v1:%v v2:%v\n", "subscribe failed", e
)
176 // Handle a unsubscribe for the different protocol levels.
177 func HandleUnsubscribe(c
*stompngo
.Connection
, d
, i
string) {
178 sbh
:= stompngo
.Headers
{}
180 switch c
.Protocol() {
181 case stompngo
.SPL_12
:
182 sbh
= sbh
.Add("id", i
)
183 case stompngo
.SPL_11
:
184 sbh
= sbh
.Add("id", i
)
185 case stompngo
.SPL_10
:
186 sbh
= sbh
.Add("destination", d
)
188 llu
.Fatalf("v1:%v v2:%v\n", "unsubscribe invalid protocol level, should not happen")
190 e
:= c
.Unsubscribe(sbh
)
192 llu
.Fatalf("v1:%v v2:%v d:%v\n", "unsubscribe failed", e
, d
)
197 // Handle ACKs for the different protocol levels.
198 func HandleAck(c
*stompngo
.Connection
, h stompngo
.Headers
, id
string) {
199 ah
:= stompngo
.Headers
{}
201 switch c
.Protocol() {
202 case stompngo
.SPL_12
:
203 ah
= ah
.Add("id", h
.Value("ack"))
204 case stompngo
.SPL_11
:
205 ah
= ah
.Add("message-id", h
.Value("message-id")).Add("subscription", id
)
206 case stompngo
.SPL_10
:
207 ah
= ah
.Add("message-id", h
.Value("message-id"))
209 llu
.Fatalf("v1:%v v2:%v\n", "ack invalid protocol level, should not happen")
211 if cv
, ok
:= h
.Contains(stompngo
.HK_RECEIPT
); ok
{
212 ah
= ah
.Add(stompngo
.HK_RECEIPT
, cv
)
216 llu
.Fatalf("v1:%v v2:%v v3:%v\n", "ack failed", e
, c
.Protocol())
221 func ShowRunParms(exampid
string) {
222 llu
.Printf("%sHOST:%v\n", exampid
, os
.Getenv("STOMP_HOST"))
223 llu
.Printf("%sPORT:%v\n", exampid
, os
.Getenv("STOMP_PORT"))
224 llu
.Printf("%sPROTOCOL:%v\n", exampid
, senv
.Protocol())
225 llu
.Printf("%sVHOST:%v\n", exampid
, senv
.Vhost())
226 llu
.Printf("%sNQS:%v\n", exampid
, Nqs())
227 llu
.Printf("%sNMSGS:%v\n", exampid
, senv
.Nmsgs())
228 llu
.Printf("%sSUBCHANCAP:%v\n", exampid
, senv
.SubChanCap())
229 llu
.Printf("%sRECVFACT:%vn", exampid
, RecvFactor())
230 llu
.Printf("%sSENDFACT:%v\n", exampid
, SendFactor())
231 llu
.Printf("%sACKMODE:%v\n", exampid
, AckMode())
234 // Return broker identity
235 func ServerIdent(c
*stompngo
.Connection
) string {
236 cdh
:= c
.ConnectResponse
237 sr
, ok
:= cdh
.Headers
.Contains("server")
244 // Common example connect logic
245 func CommonConnect(exampid
, tag
string, l
*log
.Logger
) (net
.Conn
,
246 *stompngo
.Connection
,
249 l
.Printf("%stag:%s consess:%v common_connect_starts\n",
252 // Set up the connection.
253 h
, p
:= senv
.HostAndPort()
254 hap
:= net
.JoinHostPort(h
, p
)
255 n
, e
:= net
.Dial("tcp", hap
)
260 l
.Printf("%stag:%s connsess:%s common_connect_host_and_port:%v\n",
264 // Create connect headers and connect to stompngo
265 ch
:= ConnectHeaders()
266 l
.Printf("%stag:%s connsess:%s common_connect_headers headers:%v\n",
269 conn
, e
:= stompngo
.Connect(n
, ch
)
273 l
.Printf("%stag:%s connsess:%s common_connect_complete host:%s port:%s vhost:%s protocol:%s server:%s\n",
274 exampid
, tag
, conn
.Session(),
275 h
, p
, senv
.Vhost(), conn
.Protocol(), ServerIdent(conn
))
277 // Show connect response
278 l
.Printf("%stag:%s connsess:%s common_connect_response connresp:%v\n",
279 exampid
, tag
, conn
.Session(),
280 conn
.ConnectResponse
)
282 // Show heartbeat data (if heart beats are being used)
283 if senv
.Heartbeats() != "" {
284 l
.Printf("%stag:%s connsess:%s common_connect_heart_beat_send hbsend:%v\n",
285 exampid
, tag
, conn
.Session(),
286 conn
.SendTickerInterval())
287 l
.Printf("%stag:%s connsess:%s common_connect_heart_beat_recv hbrecv:%v\n",
288 exampid
, tag
, conn
.Session(),
289 conn
.ReceiveTickerInterval())
292 l
.Printf("%stag:%s connsess:%s common_connect_local_addr:%s\n",
293 exampid
, tag
, conn
.Session(),
294 n
.LocalAddr().String())
295 l
.Printf("%stag:%s connsess:%s common_connect_remote_addr:%s\n",
296 exampid
, tag
, conn
.Session(),
297 n
.RemoteAddr().String())
303 // Common example disconnect logic
304 func CommonDisconnect(n net
.Conn
, conn
*stompngo
.Connection
,
306 l
*log
.Logger
) error
{
308 // Disconnect from the Stomp server
309 e
:= conn
.Disconnect(stompngo
.Headers
{})
313 l
.Printf("%stag:%s consess:%v common_disconnect_complete local_addr:%s remote_addr:%s\n",
314 exampid
, tag
, conn
.Session(),
315 n
.LocalAddr().String(), n
.RemoteAddr().String())
317 // Close the network connection
324 l
.Printf("%stag:%s consess:%v common_disconnect_network_close_complete\n",
325 exampid
, tag
, conn
.Session())
326 l
.Printf("%stag:%s consess:%v common_disconnect_ends\n",
327 exampid
, tag
, conn
.Session())
333 // Common example TLS connect logic
334 func CommonTLSConnect(exampid
, tag
string, l
*log
.Logger
,
335 c
*tls
.Config
) (net
.Conn
, *stompngo
.Connection
, error
) {
337 l
.Printf("%stag:%s consess:%s common_tls_connect_starts\n",
340 // Set up the connection.
341 h
, p
:= senv
.HostAndPort()
342 hap
:= net
.JoinHostPort(h
, p
)
343 n
, e
:= net
.Dial("tcp", hap
)
348 c
.ServerName
= h
// SNI
350 nc
:= tls
.Client(n
, c
) // Returns: *tls.Conn : implements net.Conn
353 if e
.Error() == "EOF" {
354 l
.Printf("%stag:%s consess:%s common_tls_handshake_EOF_Is_the_broker_port_TLS_enabled? port:%s\n",
358 l
.Fatalf("%stag:%s consess:%s common_tls_handshake_failed error:%v\n",
362 l
.Printf("%stag:%s consess:%s common_tls_handshake_complete\n",
365 l
.Printf("%stag:%s connsess:%s common_tls_connect_host_and_port:%v\n",
369 // Create connect headers and connect to stompngo
370 ch
:= ConnectHeaders()
371 l
.Printf("%stag:%s connsess:%s common_tls_connect_headers headers:%v\n",
374 conn
, e
:= stompngo
.Connect(nc
, ch
)
378 l
.Printf("%stag:%s connsess:%s common_tls_connect_complete host:%s vhost:%s protocol:%s server:%s\n",
379 exampid
, tag
, conn
.Session(),
380 h
, senv
.Vhost(), conn
.Protocol(), ServerIdent(conn
))
382 // Show connect response
383 l
.Printf("%stag:%s connsess:%s common_tls_connect_response connresp:%v\n",
384 exampid
, tag
, conn
.Session(),
385 conn
.ConnectResponse
)
387 // Show heartbeat data (if heart beats are being used)
388 if senv
.Heartbeats() != "" {
389 l
.Printf("%stag:%s connsess:%s common_tls_connect_heart_beat_send hbsend:%v\n",
390 exampid
, tag
, conn
.Session(),
391 conn
.SendTickerInterval())
392 l
.Printf("%stag:%s connsess:%s common_tls_connect_heart_beat_recv hbrecv:%v\n",
393 exampid
, tag
, conn
.Session(),
394 conn
.ReceiveTickerInterval())
397 l
.Printf("%stag:%s connsess:%s common_tls_connect_local_addr:%s\n",
398 exampid
, tag
, conn
.Session(),
399 n
.LocalAddr().String())
400 l
.Printf("%stag:%s connsess:%s common_tls_connect_remote_addr:%s\n",
401 exampid
, tag
, conn
.Session(),
402 n
.RemoteAddr().String())