mirror of
https://github.com/fhmq/hmq.git
synced 2026-05-02 06:18:33 +00:00
Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
221d00480e | ||
|
|
91733bf91e | ||
|
|
ef252550dc | ||
|
|
1058256235 | ||
|
|
5a569f14a3 | ||
|
|
93b21777ff | ||
|
|
dcf2934e1b | ||
|
|
d9e6e216b0 | ||
|
|
ca3951769a | ||
|
|
0439e7ce90 | ||
|
|
dc0f2185ab | ||
|
|
7462afcfb5 | ||
|
|
114e6f901e | ||
|
|
0cb51bd37a | ||
|
|
819b4725f2 | ||
|
|
85bdeccbfc | ||
|
|
1339a04b28 | ||
|
|
957329d85c | ||
|
|
7db7edaa17 | ||
|
|
1d6f6a4a71 | ||
|
|
123bb7210f | ||
|
|
9ad6590e83 | ||
|
|
516db49db5 | ||
|
|
a260057bfe | ||
|
|
bdd802ebfb | ||
|
|
5786e69b01 | ||
|
|
6a89b627d4 | ||
|
|
208a7cf0a8 | ||
|
|
a7fb7f1912 | ||
|
|
eeab0c6b7d | ||
|
|
4646042b7f | ||
|
|
49385e52fd | ||
|
|
3ed8625bb9 | ||
|
|
6b50060eae | ||
|
|
96277996f0 | ||
|
|
5601632a33 | ||
|
|
cc1b3239ad | ||
|
|
476d22568b | ||
|
|
c85ba76f8f | ||
|
|
f3b2924b07 | ||
|
|
6144aeb6bf |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
hmq
|
hmq
|
||||||
log
|
log
|
||||||
log/*
|
log/*
|
||||||
|
*.test
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
FROM alpine
|
FROM alpine
|
||||||
COPY hmq /
|
COPY hmq /
|
||||||
COPY broker.config /
|
COPY ssl /ssl
|
||||||
COPY tls /tls
|
|
||||||
COPY conf /conf
|
COPY conf /conf
|
||||||
|
|
||||||
EXPOSE 1883
|
EXPOSE 1883
|
||||||
201
LICENSE
Normal file
201
LICENSE
Normal file
@@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright {yyyy} {name of copyright owner}
|
||||||
|
|
||||||
|
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.
|
||||||
65
README.md
65
README.md
@@ -3,25 +3,69 @@ Free and High Performance MQTT Broker
|
|||||||
|
|
||||||
## About
|
## About
|
||||||
Golang MQTT Broker, Version 3.1.1, and Compatible
|
Golang MQTT Broker, Version 3.1.1, and Compatible
|
||||||
for [eclipse paho client](https://github.com/eclipse?utf8=%E2%9C%93&q=mqtt&type=&language=)
|
for [eclipse paho client](https://github.com/eclipse?utf8=%E2%9C%93&q=mqtt&type=&language=) and mosquitto-client
|
||||||
|
|
||||||
|
Download: [click here](https://github.com/fhmq/hmq/releases)
|
||||||
|
|
||||||
## RUNNING
|
## RUNNING
|
||||||
```bash
|
```bash
|
||||||
$ git clone https://github.com/fhmq/hmq.git
|
$ go get github.com/fhmq/hmq
|
||||||
$ cd hmq
|
$ cd $GOPATH/github.com/fhmq/hmq
|
||||||
$ go run main.go
|
$ go run main.go
|
||||||
```
|
```
|
||||||
|
|
||||||
### broker.config
|
## Usage of hmq:
|
||||||
|
~~~
|
||||||
|
Usage of ./hmq:
|
||||||
|
-w int
|
||||||
|
worker num to process message, perfer (client num)/10. (default 1024)
|
||||||
|
-worker int
|
||||||
|
worker num to process message, perfer (client num)/10. (default 1024)
|
||||||
|
-h string
|
||||||
|
Network host to listen on. (default "0.0.0.0")
|
||||||
|
-host string
|
||||||
|
Network host to listen on. (default "0.0.0.0")
|
||||||
|
-p string
|
||||||
|
Port to listen on. (default "1883")
|
||||||
|
-port string
|
||||||
|
Port to listen on. (default "1883")
|
||||||
|
-c string
|
||||||
|
config file for hmq
|
||||||
|
-config string
|
||||||
|
config file for hmq
|
||||||
|
-cluster string
|
||||||
|
Cluster ip from which members can connect.
|
||||||
|
-cluster_listen string
|
||||||
|
Cluster ip from which members can connect.
|
||||||
|
-cluster_port string
|
||||||
|
Cluster port from which members can connect.
|
||||||
|
-cp string
|
||||||
|
Cluster port from which members can connect.
|
||||||
|
-r string
|
||||||
|
Router who maintenance cluster info
|
||||||
|
-router string
|
||||||
|
Router who maintenance cluster info
|
||||||
|
-ws_path string
|
||||||
|
path for ws to listen on
|
||||||
|
-ws_port string
|
||||||
|
port for ws to listen on
|
||||||
|
-wspath string
|
||||||
|
path for ws to listen on
|
||||||
|
-wsport string
|
||||||
|
port for ws to listen on
|
||||||
|
~~~
|
||||||
|
|
||||||
|
### hmq.config
|
||||||
~~~
|
~~~
|
||||||
{
|
{
|
||||||
|
"workerNum": 4096,
|
||||||
"port": "1883",
|
"port": "1883",
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"cluster": {
|
"cluster": {
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": "1993",
|
"port": "1993"
|
||||||
"routers": ["10.10.0.11:1993","10.10.0.12:1993"]
|
|
||||||
},
|
},
|
||||||
|
"router": "127.0.0.1:9888",
|
||||||
"wsPort": "1888",
|
"wsPort": "1888",
|
||||||
"wsPath": "/ws",
|
"wsPath": "/ws",
|
||||||
"wsTLS": true,
|
"wsTLS": true,
|
||||||
@@ -58,6 +102,13 @@ $ go run main.go
|
|||||||
|
|
||||||
* Flexible ACL
|
* Flexible ACL
|
||||||
|
|
||||||
|
### Cluster
|
||||||
|
```bash
|
||||||
|
1, start router for hmq (https://github.com/fhmq/router.git)
|
||||||
|
2, config router in hmq.config ("router": "127.0.0.1:9888")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
### QUEUE SUBSCRIBE
|
### QUEUE SUBSCRIBE
|
||||||
~~~
|
~~~
|
||||||
| Prefix | Examples |
|
| Prefix | Examples |
|
||||||
@@ -128,4 +179,4 @@ Client -> | Rule1 | --nomatch--> | Rule2 | --nomatch--> | Rule3 | -->
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
* Apache License Version 2.0
|
* Apache License Version 2.0
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
theme: jekyll-theme-slate
|
|
||||||
@@ -1,10 +1,13 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hmq/lib/acl"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/fhmq/hmq/lib/acl"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
"github.com/fsnotify/fsnotify"
|
"github.com/fsnotify/fsnotify"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -40,10 +43,10 @@ func (b *Broker) handleFsEvent(event fsnotify.Event) error {
|
|||||||
case b.config.AclConf:
|
case b.config.AclConf:
|
||||||
if event.Op&fsnotify.Write == fsnotify.Write ||
|
if event.Op&fsnotify.Write == fsnotify.Write ||
|
||||||
event.Op&fsnotify.Create == fsnotify.Create {
|
event.Op&fsnotify.Create == fsnotify.Create {
|
||||||
log.Info("text:handling acl config change event:", event)
|
log.Info("text:handling acl config change event:", zap.String("filename", event.Name))
|
||||||
aclconfig, err := acl.AclConfigLoad(event.Name)
|
aclconfig, err := acl.AclConfigLoad(event.Name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("aclconfig change failed, load acl conf error: ", err)
|
log.Error("aclconfig change failed, load acl conf error: ", zap.Error(err))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
b.AclConfig = aclconfig
|
b.AclConfig = aclconfig
|
||||||
@@ -56,14 +59,14 @@ func (b *Broker) StartAclWatcher() {
|
|||||||
go func() {
|
go func() {
|
||||||
wch, e := fsnotify.NewWatcher()
|
wch, e := fsnotify.NewWatcher()
|
||||||
if e != nil {
|
if e != nil {
|
||||||
log.Error("start monitor acl config file error,", e)
|
log.Error("start monitor acl config file error,", zap.Error(e))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer wch.Close()
|
defer wch.Close()
|
||||||
|
|
||||||
for _, i := range watchList {
|
for _, i := range watchList {
|
||||||
if err := wch.Add(i); err != nil {
|
if err := wch.Add(i); err != nil {
|
||||||
log.Error("start monitor acl config file error,", err)
|
log.Error("start monitor acl config file error,", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -73,7 +76,7 @@ func (b *Broker) StartAclWatcher() {
|
|||||||
case evt := <-wch.Events:
|
case evt := <-wch.Events:
|
||||||
b.handleFsEvent(evt)
|
b.handleFsEvent(evt)
|
||||||
case err := <-wch.Errors:
|
case err := <-wch.Errors:
|
||||||
log.Error("error:", err.Error())
|
log.Error("error:", zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
320
broker/broker.go
320
broker/broker.go
@@ -1,29 +1,42 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"hmq/lib/acl"
|
|
||||||
"hmq/packets"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/fhmq/hmq/lib/acl"
|
||||||
|
|
||||||
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
|
"github.com/shirou/gopsutil/mem"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
"golang.org/x/net/websocket"
|
"golang.org/x/net/websocket"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/fhmq/hmq/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
log = logger.Get().Named("Broker")
|
||||||
)
|
)
|
||||||
|
|
||||||
type Broker struct {
|
type Broker struct {
|
||||||
id string
|
id string
|
||||||
cid uint64
|
cid uint64
|
||||||
|
mu sync.Mutex
|
||||||
config *Config
|
config *Config
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
AclConfig *acl.ACLConfig
|
AclConfig *acl.ACLConfig
|
||||||
clients sync.Map
|
clients sync.Map
|
||||||
routes sync.Map
|
routes sync.Map
|
||||||
remotes sync.Map
|
remotes sync.Map
|
||||||
|
nodes map[string]interface{}
|
||||||
sl *Sublist
|
sl *Sublist
|
||||||
rl *RetainList
|
rl *RetainList
|
||||||
queues map[string]int
|
queues map[string]int
|
||||||
@@ -35,12 +48,13 @@ func NewBroker(config *Config) (*Broker, error) {
|
|||||||
config: config,
|
config: config,
|
||||||
sl: NewSublist(),
|
sl: NewSublist(),
|
||||||
rl: NewRetainList(),
|
rl: NewRetainList(),
|
||||||
|
nodes: make(map[string]interface{}),
|
||||||
queues: make(map[string]int),
|
queues: make(map[string]int),
|
||||||
}
|
}
|
||||||
if b.config.TlsPort != "" {
|
if b.config.TlsPort != "" {
|
||||||
tlsconfig, err := NewTLSConfig(b.config.TlsInfo)
|
tlsconfig, err := NewTLSConfig(b.config.TlsInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("new tlsConfig error: ", err)
|
log.Error("new tlsConfig error", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
b.tlsConfig = tlsconfig
|
b.tlsConfig = tlsconfig
|
||||||
@@ -48,7 +62,7 @@ func NewBroker(config *Config) (*Broker, error) {
|
|||||||
if b.config.Acl {
|
if b.config.Acl {
|
||||||
aclconfig, err := acl.AclConfigLoad(b.config.AclConf)
|
aclconfig, err := acl.AclConfigLoad(b.config.AclConf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Load acl conf error: ", err)
|
log.Error("Load acl conf error", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
b.AclConfig = aclconfig
|
b.AclConfig = aclconfig
|
||||||
@@ -62,29 +76,62 @@ func (b *Broker) Start() {
|
|||||||
log.Error("broker is null")
|
log.Error("broker is null")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
StartDispatcher()
|
||||||
|
|
||||||
|
//listen clinet over tcp
|
||||||
if b.config.Port != "" {
|
if b.config.Port != "" {
|
||||||
go b.StartClientListening(false)
|
go b.StartClientListening(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//listen for cluster
|
||||||
if b.config.Cluster.Port != "" {
|
if b.config.Cluster.Port != "" {
|
||||||
go b.StartClusterListening()
|
go b.StartClusterListening()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//listen for websocket
|
||||||
if b.config.WsPort != "" {
|
if b.config.WsPort != "" {
|
||||||
go b.StartWebsocketListening()
|
go b.StartWebsocketListening()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//listen client over tls
|
||||||
if b.config.TlsPort != "" {
|
if b.config.TlsPort != "" {
|
||||||
go b.StartClientListening(true)
|
go b.StartClientListening(true)
|
||||||
}
|
}
|
||||||
if len(b.config.Cluster.Routes) > 0 {
|
|
||||||
b.ConnectToRouters()
|
//connect on other node in cluster
|
||||||
|
if b.config.Router != "" {
|
||||||
|
b.ConnectToDiscovery()
|
||||||
|
}
|
||||||
|
|
||||||
|
//system monitor
|
||||||
|
go StateMonitor()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func StateMonitor() {
|
||||||
|
v, _ := mem.VirtualMemory()
|
||||||
|
timeSticker := time.NewTicker(time.Second * 30)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-timeSticker.C:
|
||||||
|
if v.UsedPercent > 75 {
|
||||||
|
debug.FreeOSMemory()
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) StartWebsocketListening() {
|
func (b *Broker) StartWebsocketListening() {
|
||||||
path := b.config.WsPath
|
path := b.config.WsPath
|
||||||
hp := ":" + b.config.WsPort
|
hp := ":" + b.config.WsPort
|
||||||
log.Info("Start Webscoker Listening on ", hp, path)
|
log.Info("Start Websocket Listening on ", zap.String("hp", hp), zap.String("path", path))
|
||||||
http.Handle(path, websocket.Handler(b.wsHandler))
|
http.Handle(path, websocket.Handler(b.wsHandler))
|
||||||
err := http.ListenAndServe(hp, nil)
|
var err error
|
||||||
|
if b.config.WsTLS {
|
||||||
|
err = http.ListenAndServeTLS(hp, b.config.TlsInfo.CertFile, b.config.TlsInfo.KeyFile, nil)
|
||||||
|
} else {
|
||||||
|
err = http.ListenAndServe(hp, nil)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("ListenAndServe: " + err.Error())
|
log.Error("ListenAndServe: " + err.Error())
|
||||||
return
|
return
|
||||||
@@ -105,14 +152,14 @@ func (b *Broker) StartClientListening(Tls bool) {
|
|||||||
if Tls {
|
if Tls {
|
||||||
hp = b.config.TlsHost + ":" + b.config.TlsPort
|
hp = b.config.TlsHost + ":" + b.config.TlsPort
|
||||||
l, err = tls.Listen("tcp", hp, b.tlsConfig)
|
l, err = tls.Listen("tcp", hp, b.tlsConfig)
|
||||||
log.Info("Start TLS Listening client on ", hp)
|
log.Info("Start TLS Listening client on ", zap.String("hp", hp))
|
||||||
} else {
|
} else {
|
||||||
hp := b.config.Host + ":" + b.config.Port
|
hp := b.config.Host + ":" + b.config.Port
|
||||||
l, err = net.Listen("tcp", hp)
|
l, err = net.Listen("tcp", hp)
|
||||||
log.Info("Start Listening client on ", hp)
|
log.Info("Start Listening client on ", zap.String("hp", hp))
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Error listening on ", err)
|
log.Error("Error listening on ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
tmpDelay := 10 * ACCEPT_MIN_SLEEP
|
tmpDelay := 10 * ACCEPT_MIN_SLEEP
|
||||||
@@ -121,14 +168,14 @@ func (b *Broker) StartClientListening(Tls bool) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
if ne, ok := err.(net.Error); ok && ne.Temporary() {
|
if ne, ok := err.(net.Error); ok && ne.Temporary() {
|
||||||
log.Error("Temporary Client Accept Error(%v), sleeping %dms",
|
log.Error("Temporary Client Accept Error(%v), sleeping %dms",
|
||||||
ne, tmpDelay/time.Millisecond)
|
zap.Error(ne), zap.Duration("sleeping", tmpDelay/time.Millisecond))
|
||||||
time.Sleep(tmpDelay)
|
time.Sleep(tmpDelay)
|
||||||
tmpDelay *= 2
|
tmpDelay *= 2
|
||||||
if tmpDelay > ACCEPT_MAX_SLEEP {
|
if tmpDelay > ACCEPT_MAX_SLEEP {
|
||||||
tmpDelay = ACCEPT_MAX_SLEEP
|
tmpDelay = ACCEPT_MAX_SLEEP
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Error("Accept error: %v", err)
|
log.Error("Accept error: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -147,7 +194,7 @@ func (b *Broker) Handshake(conn net.Conn) bool {
|
|||||||
|
|
||||||
// Force handshake
|
// Force handshake
|
||||||
if err := nc.Handshake(); err != nil {
|
if err := nc.Handshake(); err != nil {
|
||||||
log.Error("TLS handshake error, ", err)
|
log.Error("TLS handshake error, ", zap.Error(err))
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
nc.SetReadDeadline(time.Time{})
|
nc.SetReadDeadline(time.Time{})
|
||||||
@@ -170,11 +217,11 @@ func TlsTimeout(conn *tls.Conn) {
|
|||||||
|
|
||||||
func (b *Broker) StartClusterListening() {
|
func (b *Broker) StartClusterListening() {
|
||||||
var hp string = b.config.Cluster.Host + ":" + b.config.Cluster.Port
|
var hp string = b.config.Cluster.Host + ":" + b.config.Cluster.Port
|
||||||
log.Info("Start Listening cluster on ", hp)
|
log.Info("Start Listening cluster on ", zap.String("hp", hp))
|
||||||
|
|
||||||
l, e := net.Listen("tcp", hp)
|
l, e := net.Listen("tcp", hp)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
log.Error("Error listening on ", e)
|
log.Error("Error listening on ", zap.Error(e))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,26 +232,20 @@ func (b *Broker) StartClusterListening() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
if ne, ok := err.(net.Error); ok && ne.Temporary() {
|
if ne, ok := err.(net.Error); ok && ne.Temporary() {
|
||||||
log.Error("Temporary Client Accept Error(%v), sleeping %dms",
|
log.Error("Temporary Client Accept Error(%v), sleeping %dms",
|
||||||
ne, tmpDelay/time.Millisecond)
|
zap.Error(ne), zap.Duration("sleeping", tmpDelay/time.Millisecond))
|
||||||
time.Sleep(tmpDelay)
|
time.Sleep(tmpDelay)
|
||||||
tmpDelay *= 2
|
tmpDelay *= 2
|
||||||
if tmpDelay > ACCEPT_MAX_SLEEP {
|
if tmpDelay > ACCEPT_MAX_SLEEP {
|
||||||
tmpDelay = ACCEPT_MAX_SLEEP
|
tmpDelay = ACCEPT_MAX_SLEEP
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log.Error("Accept error: %v", err)
|
log.Error("Accept error: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
tmpDelay = ACCEPT_MIN_SLEEP
|
tmpDelay = ACCEPT_MIN_SLEEP
|
||||||
|
|
||||||
go b.handleConnection(ROUTER, conn, idx)
|
go b.handleConnection(ROUTER, conn, idx)
|
||||||
if idx == 1 {
|
|
||||||
idx = 0
|
|
||||||
} else {
|
|
||||||
idx = idx + 1
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,7 +253,7 @@ func (b *Broker) handleConnection(typ int, conn net.Conn, idx uint64) {
|
|||||||
//process connect packet
|
//process connect packet
|
||||||
packet, err := packets.ReadPacket(conn)
|
packet, err := packets.ReadPacket(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("read connect packet error: ", err)
|
log.Error("read connect packet error: ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if packet == nil {
|
if packet == nil {
|
||||||
@@ -229,7 +270,7 @@ func (b *Broker) handleConnection(typ int, conn net.Conn, idx uint64) {
|
|||||||
connack.SessionPresent = msg.CleanSession
|
connack.SessionPresent = msg.CleanSession
|
||||||
err = connack.Write(conn)
|
err = connack.Write(conn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send connack error, ", err)
|
log.Error("send connack error, ", zap.Error(err), zap.String("clientID", msg.ClientIdentifier))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -257,6 +298,7 @@ func (b *Broker) handleConnection(typ int, conn net.Conn, idx uint64) {
|
|||||||
conn: conn,
|
conn: conn,
|
||||||
info: info,
|
info: info,
|
||||||
}
|
}
|
||||||
|
|
||||||
c.init()
|
c.init()
|
||||||
|
|
||||||
cid := c.info.clientID
|
cid := c.info.clientID
|
||||||
@@ -268,64 +310,172 @@ func (b *Broker) handleConnection(typ int, conn net.Conn, idx uint64) {
|
|||||||
switch typ {
|
switch typ {
|
||||||
case CLIENT:
|
case CLIENT:
|
||||||
msgPool = MSGPool[idx%MessagePoolNum].GetPool()
|
msgPool = MSGPool[idx%MessagePoolNum].GetPool()
|
||||||
|
c.mp = msgPool
|
||||||
old, exist = b.clients.Load(cid)
|
old, exist = b.clients.Load(cid)
|
||||||
|
if exist {
|
||||||
|
log.Warn("client exist, close old...", zap.String("clientID", c.info.clientID))
|
||||||
|
ol, ok := old.(*client)
|
||||||
|
if ok {
|
||||||
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
|
ol.mp.queue <- msg
|
||||||
|
}
|
||||||
|
}
|
||||||
b.clients.Store(cid, c)
|
b.clients.Store(cid, c)
|
||||||
case ROUTER:
|
case ROUTER:
|
||||||
msgPool = MSGPool[(MessagePoolNum + idx)].GetPool()
|
msgPool = MSGPool[(MessagePoolNum + idx)].GetPool()
|
||||||
|
c.mp = msgPool
|
||||||
old, exist = b.routes.Load(cid)
|
old, exist = b.routes.Load(cid)
|
||||||
|
if exist {
|
||||||
|
log.Warn("router exist, close old...")
|
||||||
|
ol, ok := old.(*client)
|
||||||
|
if ok {
|
||||||
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
|
ol.mp.queue <- msg
|
||||||
|
}
|
||||||
|
}
|
||||||
b.routes.Store(cid, c)
|
b.routes.Store(cid, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
if exist {
|
c.readLoop()
|
||||||
log.Warn("client or routers exist, close old...")
|
|
||||||
ol, ok := old.(*client)
|
|
||||||
if ok {
|
|
||||||
ol.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.readLoop(msgPool)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) ConnectToRouters() {
|
func (b *Broker) ConnectToDiscovery() {
|
||||||
for i := 0; i < len(b.config.Cluster.Routes); i++ {
|
var conn net.Conn
|
||||||
url := b.config.Cluster.Routes[i]
|
var err error
|
||||||
go b.connectRouter(url, "")
|
var tempDelay time.Duration = 0
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Broker) connectRouter(url, remoteID string) {
|
|
||||||
for {
|
for {
|
||||||
conn, err := net.Dial("tcp", url)
|
conn, err = net.Dial("tcp", b.config.Router)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Error trying to connect to route: ", err)
|
log.Error("Error trying to connect to route: ", zap.Error(err))
|
||||||
select {
|
log.Debug("Connect to route timeout ,retry...")
|
||||||
case <-time.After(DEFAULT_ROUTE_CONNECT):
|
|
||||||
log.Debug("Connect to route timeout ,retry...")
|
if 0 == tempDelay {
|
||||||
continue
|
tempDelay = 1 * time.Second
|
||||||
|
} else {
|
||||||
|
tempDelay *= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if max := 20 * time.Second; tempDelay > max {
|
||||||
|
tempDelay = max
|
||||||
|
}
|
||||||
|
time.Sleep(tempDelay)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
log.Debug("connect to router success :", zap.String("Router", b.config.Router))
|
||||||
|
|
||||||
|
cid := b.id
|
||||||
|
info := info{
|
||||||
|
clientID: cid,
|
||||||
|
keepalive: 60,
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &client{
|
||||||
|
typ: CLUSTER,
|
||||||
|
broker: b,
|
||||||
|
conn: conn,
|
||||||
|
info: info,
|
||||||
|
}
|
||||||
|
|
||||||
|
c.init()
|
||||||
|
|
||||||
|
c.SendConnect()
|
||||||
|
c.SendInfo()
|
||||||
|
|
||||||
|
c.mp = &MSGPool[(MessagePoolNum + 2)]
|
||||||
|
go c.readLoop()
|
||||||
|
go c.StartPing()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Broker) connectRouter(id, addr string) {
|
||||||
|
var conn net.Conn
|
||||||
|
var err error
|
||||||
|
var timeDelay time.Duration = 0
|
||||||
|
retryTimes := 0
|
||||||
|
max := 32 * time.Second
|
||||||
|
for {
|
||||||
|
|
||||||
|
if !b.checkNodeExist(id, addr) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err = net.Dial("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Error trying to connect to route: ", zap.Error(err))
|
||||||
|
|
||||||
|
if retryTimes > 50 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Debug("Connect to route timeout ,retry...")
|
||||||
|
|
||||||
|
if 0 == timeDelay {
|
||||||
|
timeDelay = 1 * time.Second
|
||||||
|
} else {
|
||||||
|
timeDelay *= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if timeDelay > max {
|
||||||
|
timeDelay = max
|
||||||
|
}
|
||||||
|
time.Sleep(timeDelay)
|
||||||
|
retryTimes++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
route := route{
|
||||||
|
remoteID: id,
|
||||||
|
remoteUrl: addr,
|
||||||
|
}
|
||||||
|
cid := GenUniqueId()
|
||||||
|
|
||||||
|
info := info{
|
||||||
|
clientID: cid,
|
||||||
|
keepalive: 60,
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &client{
|
||||||
|
broker: b,
|
||||||
|
typ: REMOTE,
|
||||||
|
conn: conn,
|
||||||
|
route: route,
|
||||||
|
info: info,
|
||||||
|
}
|
||||||
|
c.init()
|
||||||
|
b.remotes.Store(cid, c)
|
||||||
|
|
||||||
|
c.mp = MSGPool[(MessagePoolNum + 1)].GetPool()
|
||||||
|
|
||||||
|
c.SendConnect()
|
||||||
|
// c.SendInfo()
|
||||||
|
|
||||||
|
go c.readLoop()
|
||||||
|
go c.StartPing()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Broker) checkNodeExist(id, url string) bool {
|
||||||
|
if id == b.id {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range b.nodes {
|
||||||
|
if k == id {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
//skip
|
||||||
|
l, ok := v.(string)
|
||||||
|
if ok {
|
||||||
|
if url == l {
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
route := &route{
|
|
||||||
remoteID: remoteID,
|
|
||||||
remoteUrl: url,
|
|
||||||
}
|
|
||||||
cid := GenUniqueId()
|
|
||||||
info := info{
|
|
||||||
clientID: cid,
|
|
||||||
}
|
|
||||||
c := &client{
|
|
||||||
typ: REMOTE,
|
|
||||||
conn: conn,
|
|
||||||
route: route,
|
|
||||||
info: info,
|
|
||||||
}
|
|
||||||
b.remotes.Store(cid, c)
|
|
||||||
c.SendConnect()
|
|
||||||
c.SendInfo()
|
|
||||||
// s.createRemote(conn, route)
|
|
||||||
// msgPool := MSGPool[(MessagePoolNum + 1)].GetPool()
|
|
||||||
c.StartPing()
|
|
||||||
// c.readLoop(msgPool)
|
|
||||||
}
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) CheckRemoteExist(remoteID, url string) bool {
|
func (b *Broker) CheckRemoteExist(remoteID, url string) bool {
|
||||||
@@ -334,9 +484,7 @@ func (b *Broker) CheckRemoteExist(remoteID, url string) bool {
|
|||||||
v, ok := value.(*client)
|
v, ok := value.(*client)
|
||||||
if ok {
|
if ok {
|
||||||
if v.route.remoteUrl == url {
|
if v.route.remoteUrl == url {
|
||||||
// if v.route.remoteID == "" || v.route.remoteID != remoteID {
|
|
||||||
v.route.remoteID = remoteID
|
v.route.remoteID = remoteID
|
||||||
// }
|
|
||||||
exist = true
|
exist = true
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -359,14 +507,16 @@ func (b *Broker) SendLocalSubsToRouter(c *client) {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
err := c.WriterPacket(subInfo)
|
if len(subInfo.Topics) > 0 {
|
||||||
if err != nil {
|
err := c.WriterPacket(subInfo)
|
||||||
log.Error("Send localsubs To Router error :", err)
|
if err != nil {
|
||||||
|
log.Error("Send localsubs To Router error :", zap.Error(err))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) BroadcastInfoMessage(remoteID string, msg *packets.PublishPacket) {
|
func (b *Broker) BroadcastInfoMessage(remoteID string, msg *packets.PublishPacket) {
|
||||||
b.remotes.Range(func(key, value interface{}) bool {
|
b.routes.Range(func(key, value interface{}) bool {
|
||||||
r, ok := value.(*client)
|
r, ok := value.(*client)
|
||||||
if ok {
|
if ok {
|
||||||
if r.route.remoteID == remoteID {
|
if r.route.remoteID == remoteID {
|
||||||
@@ -381,7 +531,8 @@ func (b *Broker) BroadcastInfoMessage(remoteID string, msg *packets.PublishPacke
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) BroadcastSubOrUnsubMessage(packet packets.ControlPacket) {
|
func (b *Broker) BroadcastSubOrUnsubMessage(packet packets.ControlPacket) {
|
||||||
b.remotes.Range(func(key, value interface{}) bool {
|
|
||||||
|
b.routes.Range(func(key, value interface{}) bool {
|
||||||
r, ok := value.(*client)
|
r, ok := value.(*client)
|
||||||
if ok {
|
if ok {
|
||||||
r.WriterPacket(packet)
|
r.WriterPacket(packet)
|
||||||
@@ -408,7 +559,6 @@ func (b *Broker) removeClient(c *client) {
|
|||||||
func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
||||||
topic := packet.TopicName
|
topic := packet.TopicName
|
||||||
r := b.sl.Match(topic)
|
r := b.sl.Match(topic)
|
||||||
// log.Info("psubs num: ", len(r.psubs))
|
|
||||||
if len(r.psubs) == 0 {
|
if len(r.psubs) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -417,7 +567,7 @@ func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
|||||||
if sub != nil {
|
if sub != nil {
|
||||||
err := sub.client.WriterPacket(packet)
|
err := sub.client.WriterPacket(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("process message for psub error, ", err)
|
log.Error("process message for psub error, ", zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -425,14 +575,12 @@ func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
|||||||
|
|
||||||
func (b *Broker) BroadcastUnSubscribe(subs map[string]*subscription) {
|
func (b *Broker) BroadcastUnSubscribe(subs map[string]*subscription) {
|
||||||
|
|
||||||
ubsub := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket)
|
unsub := packets.NewControlPacket(packets.Unsubscribe).(*packets.UnsubscribePacket)
|
||||||
for topic, _ := range subs {
|
for topic, _ := range subs {
|
||||||
// topic := sub.topic
|
unsub.Topics = append(unsub.Topics, topic)
|
||||||
// if sub.queue {
|
|
||||||
// topic = "$queue/" + sub.topic
|
|
||||||
// }
|
|
||||||
ubsub.Topics = append(ubsub.Topics, topic)
|
|
||||||
}
|
}
|
||||||
b.BroadcastSubOrUnsubMessage(ubsub)
|
|
||||||
|
|
||||||
|
if len(unsub.Topics) > 0 {
|
||||||
|
b.BroadcastSubOrUnsubMessage(unsub)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
210
broker/client.go
210
broker/client.go
@@ -1,24 +1,31 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hmq/packets"
|
|
||||||
"net"
|
"net"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// special pub topic for cluster info BrokerInfoTopic
|
// special pub topic for cluster info BrokerInfoTopic
|
||||||
BrokerInfoTopic = "broker001info/brokerinfo"
|
BrokerInfoTopic = "broker000100101info"
|
||||||
// CLIENT is an end user.
|
// CLIENT is an end user.
|
||||||
CLIENT = 0
|
CLIENT = 0
|
||||||
// ROUTER is another router in the cluster.
|
// ROUTER is another router in the cluster.
|
||||||
ROUTER = 1
|
ROUTER = 1
|
||||||
//REMOTE is the router connect to other cluster
|
//REMOTE is the router connect to other cluster
|
||||||
REMOTE = 2
|
REMOTE = 2
|
||||||
|
CLUSTER = 3
|
||||||
|
)
|
||||||
|
const (
|
||||||
|
Connected = 1
|
||||||
|
Disconnected = 2
|
||||||
)
|
)
|
||||||
|
|
||||||
type client struct {
|
type client struct {
|
||||||
@@ -27,7 +34,11 @@ type client struct {
|
|||||||
broker *Broker
|
broker *Broker
|
||||||
conn net.Conn
|
conn net.Conn
|
||||||
info info
|
info info
|
||||||
route *route
|
route route
|
||||||
|
status int
|
||||||
|
closed chan int
|
||||||
|
smu sync.RWMutex
|
||||||
|
mp *MessagePool
|
||||||
subs map[string]*subscription
|
subs map[string]*subscription
|
||||||
rsubs map[string]*subInfo
|
rsubs map[string]*subInfo
|
||||||
}
|
}
|
||||||
@@ -64,47 +75,72 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func (c *client) init() {
|
func (c *client) init() {
|
||||||
typ := c.typ
|
c.smu.Lock()
|
||||||
if typ == ROUTER {
|
defer c.smu.Unlock()
|
||||||
c.rsubs = make(map[string]*subInfo)
|
c.status = Connected
|
||||||
} else if typ == CLIENT {
|
c.closed = make(chan int, 1)
|
||||||
c.subs = make(map[string]*subscription, 10)
|
|
||||||
}
|
c.rsubs = make(map[string]*subInfo)
|
||||||
|
c.subs = make(map[string]*subscription, 10)
|
||||||
c.info.localIP = strings.Split(c.conn.LocalAddr().String(), ":")[0]
|
c.info.localIP = strings.Split(c.conn.LocalAddr().String(), ":")[0]
|
||||||
c.info.remoteIP = strings.Split(c.conn.RemoteAddr().String(), ":")[0]
|
c.info.remoteIP = strings.Split(c.conn.RemoteAddr().String(), ":")[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) readLoop(msgPool *MessagePool) {
|
func (c *client) keepAlive(ch chan int) {
|
||||||
|
defer close(ch)
|
||||||
|
keepalive := time.Duration(c.info.keepalive*3/2) * time.Second
|
||||||
|
timer := time.NewTimer(keepalive)
|
||||||
|
msgPool := c.mp
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ch:
|
||||||
|
timer.Reset(keepalive)
|
||||||
|
case <-timer.C:
|
||||||
|
if c.typ == REMOTE || c.typ == CLUSTER {
|
||||||
|
timer.Reset(keepalive)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log.Error("Client exceeded timeout, disconnecting. ", zap.String("ClientID", c.info.clientID), zap.Uint16("keepalive", c.info.keepalive))
|
||||||
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
|
msgPool.queue <- msg
|
||||||
|
timer.Stop()
|
||||||
|
return
|
||||||
|
case _, ok := <-c.closed:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *client) readLoop() {
|
||||||
nc := c.conn
|
nc := c.conn
|
||||||
|
msgPool := c.mp
|
||||||
if nc == nil || msgPool == nil {
|
if nc == nil || msgPool == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
lastIn := uint16(time.Now().Unix())
|
ch := make(chan int, 1000)
|
||||||
var nowTime uint16
|
go c.keepAlive(ch)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
nowTime = uint16(time.Now().Unix())
|
|
||||||
if 0 != c.info.keepalive && nowTime-lastIn > c.info.keepalive*3/2 {
|
|
||||||
log.Errorf("Client %s has exceeded timeout, disconnecting.\n", c.info.clientID)
|
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
|
||||||
msgPool.queue <- msg
|
|
||||||
return
|
|
||||||
}
|
|
||||||
packet, err := packets.ReadPacket(nc)
|
packet, err := packets.ReadPacket(nc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("read packet error: ", err)
|
log.Error("read packet error: ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
break
|
||||||
msgPool.queue <- msg
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
// log.Info("recv buf: ", packet)
|
|
||||||
lastIn = uint16(time.Now().Unix())
|
ch <- 1
|
||||||
|
|
||||||
msg := &Message{
|
msg := &Message{
|
||||||
client: c,
|
client: c,
|
||||||
packet: packet,
|
packet: packet,
|
||||||
}
|
}
|
||||||
msgPool.queue <- msg
|
msgPool.queue <- msg
|
||||||
}
|
}
|
||||||
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
|
msgPool.queue <- msg
|
||||||
msgPool.Reduce()
|
msgPool.Reduce()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,53 +150,49 @@ func ProcessMessage(msg *Message) {
|
|||||||
if ca == nil {
|
if ca == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
log.Debug("Recv message from client,", zap.String("ClientID", c.info.clientID))
|
||||||
switch ca.(type) {
|
switch ca.(type) {
|
||||||
case *packets.ConnackPacket:
|
case *packets.ConnackPacket:
|
||||||
// log.Info("Recv conack message..........")
|
|
||||||
case *packets.ConnectPacket:
|
case *packets.ConnectPacket:
|
||||||
// log.Info("Recv connect message..........")
|
|
||||||
case *packets.PublishPacket:
|
case *packets.PublishPacket:
|
||||||
// log.Info("Recv publish message..........")
|
|
||||||
packet := ca.(*packets.PublishPacket)
|
packet := ca.(*packets.PublishPacket)
|
||||||
c.ProcessPublish(packet)
|
c.ProcessPublish(packet)
|
||||||
case *packets.PubackPacket:
|
case *packets.PubackPacket:
|
||||||
//log.Info("Recv publish ack message..........")
|
|
||||||
case *packets.PubrecPacket:
|
case *packets.PubrecPacket:
|
||||||
//log.Info("Recv publish rec message..........")
|
|
||||||
case *packets.PubrelPacket:
|
case *packets.PubrelPacket:
|
||||||
//log.Info("Recv publish rel message..........")
|
|
||||||
case *packets.PubcompPacket:
|
case *packets.PubcompPacket:
|
||||||
//log.Info("Recv publish ack message..........")
|
|
||||||
case *packets.SubscribePacket:
|
case *packets.SubscribePacket:
|
||||||
// log.Info("Recv subscribe message.....")
|
|
||||||
packet := ca.(*packets.SubscribePacket)
|
packet := ca.(*packets.SubscribePacket)
|
||||||
c.ProcessSubscribe(packet)
|
c.ProcessSubscribe(packet)
|
||||||
case *packets.SubackPacket:
|
case *packets.SubackPacket:
|
||||||
// log.Info("Recv suback message.....")
|
|
||||||
case *packets.UnsubscribePacket:
|
case *packets.UnsubscribePacket:
|
||||||
// log.Info("Recv unsubscribe message.....")
|
|
||||||
packet := ca.(*packets.UnsubscribePacket)
|
packet := ca.(*packets.UnsubscribePacket)
|
||||||
c.ProcessUnSubscribe(packet)
|
c.ProcessUnSubscribe(packet)
|
||||||
case *packets.UnsubackPacket:
|
case *packets.UnsubackPacket:
|
||||||
//log.Info("Recv unsuback message.....")
|
|
||||||
case *packets.PingreqPacket:
|
case *packets.PingreqPacket:
|
||||||
// log.Info("Recv PINGREQ message..........")
|
|
||||||
c.ProcessPing()
|
c.ProcessPing()
|
||||||
case *packets.PingrespPacket:
|
case *packets.PingrespPacket:
|
||||||
//log.Info("Recv PINGRESP message..........")
|
|
||||||
case *packets.DisconnectPacket:
|
case *packets.DisconnectPacket:
|
||||||
// log.Info("Recv DISCONNECT message.......")
|
|
||||||
c.Close()
|
c.Close()
|
||||||
default:
|
default:
|
||||||
log.Info("Recv Unknow message.......")
|
log.Info("Recv Unknow message.......", zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ProcessPublish(packet *packets.PublishPacket) {
|
func (c *client) ProcessPublish(packet *packets.PublishPacket) {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
topic := packet.TopicName
|
topic := packet.TopicName
|
||||||
|
if topic == BrokerInfoTopic && c.typ == CLUSTER {
|
||||||
|
c.ProcessInfo(packet)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if !c.CheckTopicAuth(PUB, topic) {
|
if !c.CheckTopicAuth(PUB, topic) {
|
||||||
log.Error("Pub Topics Auth failed, ", topic)
|
log.Error("Pub Topics Auth failed, ", zap.String("topic", topic), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,21 +203,21 @@ func (c *client) ProcessPublish(packet *packets.PublishPacket) {
|
|||||||
puback := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
puback := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
|
||||||
puback.MessageID = packet.MessageID
|
puback.MessageID = packet.MessageID
|
||||||
if err := c.WriterPacket(puback); err != nil {
|
if err := c.WriterPacket(puback); err != nil {
|
||||||
log.Error("send puback error, ", err)
|
log.Error("send puback error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.ProcessPublishMessage(packet)
|
c.ProcessPublishMessage(packet)
|
||||||
case QosExactlyOnce:
|
case QosExactlyOnce:
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
log.Error("publish with unknown qos")
|
log.Error("publish with unknown qos", zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if packet.Retain {
|
if packet.Retain {
|
||||||
if b := c.broker; b != nil {
|
if b := c.broker; b != nil {
|
||||||
err := b.rl.Insert(topic, packet)
|
err := b.rl.Insert(topic, packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Insert Retain Message error: ", err)
|
log.Error("Insert Retain Message error: ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -193,6 +225,9 @@ func (c *client) ProcessPublish(packet *packets.PublishPacket) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
b := c.broker
|
b := c.broker
|
||||||
if b == nil {
|
if b == nil {
|
||||||
@@ -209,14 +244,14 @@ func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
|||||||
|
|
||||||
for _, sub := range r.psubs {
|
for _, sub := range r.psubs {
|
||||||
if sub.client.typ == ROUTER {
|
if sub.client.typ == ROUTER {
|
||||||
if typ == ROUTER {
|
if typ != CLIENT {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if sub != nil {
|
if sub != nil {
|
||||||
err := sub.client.WriterPacket(packet)
|
err := sub.client.WriterPacket(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("process message for psub error, ", err)
|
log.Error("process message for psub error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -229,7 +264,7 @@ func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
|||||||
// log.Info("queue index : ", cnt)
|
// log.Info("queue index : ", cnt)
|
||||||
for _, sub := range r.qsubs {
|
for _, sub := range r.qsubs {
|
||||||
if sub.client.typ == ROUTER {
|
if sub.client.typ == ROUTER {
|
||||||
if c.typ == ROUTER {
|
if typ != CLIENT {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -242,7 +277,7 @@ func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
|||||||
if sub != nil {
|
if sub != nil {
|
||||||
err := sub.client.WriterPacket(packet)
|
err := sub.client.WriterPacket(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send publish error, ", err)
|
log.Error("send publish error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -277,6 +312,10 @@ func getQueueSubscribeNum(qsubs []*subscription) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
b := c.broker
|
b := c.broker
|
||||||
if b == nil {
|
if b == nil {
|
||||||
return
|
return
|
||||||
@@ -292,7 +331,7 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
t := topic
|
t := topic
|
||||||
//check topic auth for client
|
//check topic auth for client
|
||||||
if !c.CheckTopicAuth(SUB, topic) {
|
if !c.CheckTopicAuth(SUB, topic) {
|
||||||
log.Error("Sub topic Auth failed: ", topic)
|
log.Error("Sub topic Auth failed: ", zap.String("topic", topic), zap.String("ClientID", c.info.clientID))
|
||||||
retcodes = append(retcodes, QosFailure)
|
retcodes = append(retcodes, QosFailure)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -339,7 +378,7 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
}
|
}
|
||||||
err := b.sl.Insert(sub)
|
err := b.sl.Insert(sub)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Insert subscription error: ", err)
|
log.Error("Insert subscription error: ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
retcodes = append(retcodes, QosFailure)
|
retcodes = append(retcodes, QosFailure)
|
||||||
} else {
|
} else {
|
||||||
retcodes = append(retcodes, qoss[i])
|
retcodes = append(retcodes, qoss[i])
|
||||||
@@ -349,7 +388,7 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
|
|
||||||
err := c.WriterPacket(suback)
|
err := c.WriterPacket(suback)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send suback error, ", err)
|
log.Error("send suback error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//broadcast subscribe message
|
//broadcast subscribe message
|
||||||
@@ -361,7 +400,7 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
for _, t := range topics {
|
for _, t := range topics {
|
||||||
packets := b.rl.Match(t)
|
packets := b.rl.Match(t)
|
||||||
for _, packet := range packets {
|
for _, packet := range packets {
|
||||||
log.Info("process retain message: ", packet)
|
log.Info("process retain message: ", zap.Any("packet", packet), zap.String("ClientID", c.info.clientID))
|
||||||
if packet != nil {
|
if packet != nil {
|
||||||
c.WriterPacket(packet)
|
c.WriterPacket(packet)
|
||||||
}
|
}
|
||||||
@@ -370,6 +409,9 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ProcessUnSubscribe(packet *packets.UnsubscribePacket) {
|
func (c *client) ProcessUnSubscribe(packet *packets.UnsubscribePacket) {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
b := c.broker
|
b := c.broker
|
||||||
if b == nil {
|
if b == nil {
|
||||||
return
|
return
|
||||||
@@ -378,29 +420,25 @@ func (c *client) ProcessUnSubscribe(packet *packets.UnsubscribePacket) {
|
|||||||
topics := packet.Topics
|
topics := packet.Topics
|
||||||
|
|
||||||
for _, t := range topics {
|
for _, t := range topics {
|
||||||
var sub *subscription
|
|
||||||
ok := false
|
|
||||||
switch typ {
|
switch typ {
|
||||||
case CLIENT:
|
case CLIENT:
|
||||||
sub, ok = c.subs[t]
|
sub, ok := c.subs[t]
|
||||||
|
if ok {
|
||||||
|
c.unsubscribe(sub)
|
||||||
|
}
|
||||||
case ROUTER:
|
case ROUTER:
|
||||||
subinfo, ok := c.rsubs[t]
|
subinfo, ok := c.rsubs[t]
|
||||||
if ok {
|
if ok {
|
||||||
subinfo.num = subinfo.num - 1
|
subinfo.num = subinfo.num - 1
|
||||||
if subinfo.num < 1 {
|
if subinfo.num < 1 {
|
||||||
sub = subinfo.sub
|
|
||||||
delete(c.rsubs, t)
|
delete(c.rsubs, t)
|
||||||
|
c.unsubscribe(subinfo.sub)
|
||||||
} else {
|
} else {
|
||||||
c.rsubs[t] = subinfo
|
c.rsubs[t] = subinfo
|
||||||
sub = nil
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ok {
|
|
||||||
go c.unsubscribe(sub)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -409,7 +447,7 @@ func (c *client) ProcessUnSubscribe(packet *packets.UnsubscribePacket) {
|
|||||||
|
|
||||||
err := c.WriterPacket(unsuback)
|
err := c.WriterPacket(unsuback)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send unsuback error, ", err)
|
log.Error("send unsuback error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// //process ubsubscribe message
|
// //process ubsubscribe message
|
||||||
@@ -432,15 +470,36 @@ func (c *client) unsubscribe(sub *subscription) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) ProcessPing() {
|
func (c *client) ProcessPing() {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
resp := packets.NewControlPacket(packets.Pingresp).(*packets.PingrespPacket)
|
resp := packets.NewControlPacket(packets.Pingresp).(*packets.PingrespPacket)
|
||||||
err := c.WriterPacket(resp)
|
err := c.WriterPacket(resp)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send PingResponse error, ", err)
|
log.Error("send PingResponse error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) Close() {
|
func (c *client) Close() {
|
||||||
|
c.smu.Lock()
|
||||||
|
if c.status == Disconnected {
|
||||||
|
c.smu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
//wait for message complete
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
c.status = Disconnected
|
||||||
|
|
||||||
|
if c.conn != nil {
|
||||||
|
c.conn.Close()
|
||||||
|
c.conn = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c.smu.Unlock()
|
||||||
|
|
||||||
|
close(c.closed)
|
||||||
|
|
||||||
b := c.broker
|
b := c.broker
|
||||||
subs := c.subs
|
subs := c.subs
|
||||||
if b != nil {
|
if b != nil {
|
||||||
@@ -448,7 +507,7 @@ func (c *client) Close() {
|
|||||||
for _, sub := range subs {
|
for _, sub := range subs {
|
||||||
err := b.sl.Remove(sub)
|
err := b.sl.Remove(sub)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("closed client but remove sublist error, ", err)
|
log.Error("closed client but remove sublist error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.typ == CLIENT {
|
if c.typ == CLIENT {
|
||||||
@@ -457,14 +516,23 @@ func (c *client) Close() {
|
|||||||
if c.info.willMsg != nil {
|
if c.info.willMsg != nil {
|
||||||
b.PublishMessage(c.info.willMsg)
|
b.PublishMessage(c.info.willMsg)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
if c.conn != nil {
|
if c.typ == CLUSTER {
|
||||||
c.conn.Close()
|
b.ConnectToDiscovery()
|
||||||
c.conn = nil
|
}
|
||||||
|
|
||||||
|
//do reconnect
|
||||||
|
if c.typ == REMOTE {
|
||||||
|
go b.connectRouter(c.route.remoteID, c.route.remoteUrl)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) WriterPacket(packet packets.ControlPacket) error {
|
func (c *client) WriterPacket(packet packets.ControlPacket) error {
|
||||||
|
if packet == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
c.mu.Lock()
|
c.mu.Lock()
|
||||||
err := packet.Write(c.conn)
|
err := packet.Write(c.conn)
|
||||||
c.mu.Unlock()
|
c.mu.Unlock()
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"crypto/x509"
|
"crypto/x509"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"go.uber.org/zap"
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
CONFIGFILE = "hmq.config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@@ -19,6 +19,7 @@ type Config struct {
|
|||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
Port string `json:"port"`
|
Port string `json:"port"`
|
||||||
Cluster RouteInfo `json:"cluster"`
|
Cluster RouteInfo `json:"cluster"`
|
||||||
|
Router string `json:"router"`
|
||||||
TlsHost string `json:"tlsHost"`
|
TlsHost string `json:"tlsHost"`
|
||||||
TlsPort string `json:"tlsPort"`
|
TlsPort string `json:"tlsPort"`
|
||||||
WsPath string `json:"wsPath"`
|
WsPath string `json:"wsPath"`
|
||||||
@@ -30,9 +31,8 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type RouteInfo struct {
|
type RouteInfo struct {
|
||||||
Host string `json:"host"`
|
Host string `json:"host"`
|
||||||
Port string `json:"port"`
|
Port string `json:"port"`
|
||||||
Routes []string `json:"routes"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type TLSInfo struct {
|
type TLSInfo struct {
|
||||||
@@ -42,11 +42,60 @@ type TLSInfo struct {
|
|||||||
KeyFile string `json:"keyFile"`
|
KeyFile string `json:"keyFile"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func LoadConfig() (*Config, error) {
|
var DefaultConfig *Config = &Config{
|
||||||
|
Worker: 4096,
|
||||||
|
Host: "0.0.0.0",
|
||||||
|
Port: "1883",
|
||||||
|
Acl: false,
|
||||||
|
}
|
||||||
|
|
||||||
content, err := ioutil.ReadFile(CONFIGFILE)
|
func ConfigureConfig() (*Config, error) {
|
||||||
|
config := &Config{}
|
||||||
|
var (
|
||||||
|
configFile string
|
||||||
|
)
|
||||||
|
flag.IntVar(&config.Worker, "w", 1024, "worker num to process message, perfer (client num)/10.")
|
||||||
|
flag.IntVar(&config.Worker, "worker", 1024, "worker num to process message, perfer (client num)/10.")
|
||||||
|
flag.StringVar(&config.Port, "port", "1883", "Port to listen on.")
|
||||||
|
flag.StringVar(&config.Port, "p", "1883", "Port to listen on.")
|
||||||
|
flag.StringVar(&config.Host, "host", "0.0.0.0", "Network host to listen on.")
|
||||||
|
flag.StringVar(&config.Host, "h", "0.0.0.0", "Network host to listen on.")
|
||||||
|
flag.StringVar(&config.Cluster.Host, "cluster", "", "Cluster ip from which members can connect.")
|
||||||
|
flag.StringVar(&config.Cluster.Host, "cluster_listen", "", "Cluster ip from which members can connect.")
|
||||||
|
flag.StringVar(&config.Cluster.Port, "cp", "", "Cluster port from which members can connect.")
|
||||||
|
flag.StringVar(&config.Cluster.Port, "cluster_port", "", "Cluster port from which members can connect.")
|
||||||
|
flag.StringVar(&config.Router, "r", "", "Router who maintenance cluster info")
|
||||||
|
flag.StringVar(&config.Router, "router", "", "Router who maintenance cluster info")
|
||||||
|
flag.StringVar(&config.WsPort, "wsport", "", "port for ws to listen on")
|
||||||
|
flag.StringVar(&config.WsPort, "ws_port", "", "port for ws to listen on")
|
||||||
|
flag.StringVar(&config.WsPath, "wspath", "", "path for ws to listen on")
|
||||||
|
flag.StringVar(&config.WsPath, "ws_path", "", "path for ws to listen on")
|
||||||
|
flag.StringVar(&configFile, "config", "", "config file for hmq")
|
||||||
|
flag.StringVar(&configFile, "c", "", "config file for hmq")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if configFile != "" {
|
||||||
|
tmpConfig, e := LoadConfig(configFile)
|
||||||
|
if e != nil {
|
||||||
|
return nil, e
|
||||||
|
} else {
|
||||||
|
config = tmpConfig
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := config.check(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return config, nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadConfig(filename string) (*Config, error) {
|
||||||
|
|
||||||
|
content, err := ioutil.ReadFile(filename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Read config file error: ", err)
|
log.Error("Read config file error: ", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// log.Info(string(content))
|
// log.Info(string(content))
|
||||||
@@ -54,10 +103,15 @@ func LoadConfig() (*Config, error) {
|
|||||||
var config Config
|
var config Config
|
||||||
err = json.Unmarshal(content, &config)
|
err = json.Unmarshal(content, &config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Unmarshal config file error: ", err)
|
log.Error("Unmarshal config file error: ", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return &config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (config *Config) check() error {
|
||||||
|
|
||||||
if config.Worker == 0 {
|
if config.Worker == 0 {
|
||||||
config.Worker = 1024
|
config.Worker = 1024
|
||||||
}
|
}
|
||||||
@@ -75,29 +129,33 @@ func LoadConfig() (*Config, error) {
|
|||||||
config.Cluster.Host = "0.0.0.0"
|
config.Cluster.Host = "0.0.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if config.Router != "" {
|
||||||
|
if config.Cluster.Port == "" {
|
||||||
|
return errors.New("cluster port is null")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if config.TlsPort != "" {
|
if config.TlsPort != "" {
|
||||||
if config.TlsInfo.CertFile == "" || config.TlsInfo.KeyFile == "" {
|
if config.TlsInfo.CertFile == "" || config.TlsInfo.KeyFile == "" {
|
||||||
log.Error("tls config error, no cert or key file.")
|
log.Error("tls config error, no cert or key file.")
|
||||||
return nil, err
|
return errors.New("tls config error, no cert or key file.")
|
||||||
}
|
}
|
||||||
if config.TlsHost == "" {
|
if config.TlsHost == "" {
|
||||||
config.TlsHost = "0.0.0.0"
|
config.TlsHost = "0.0.0.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
return &config, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewTLSConfig(tlsInfo TLSInfo) (*tls.Config, error) {
|
func NewTLSConfig(tlsInfo TLSInfo) (*tls.Config, error) {
|
||||||
|
|
||||||
cert, err := tls.LoadX509KeyPair(tlsInfo.CertFile, tlsInfo.KeyFile)
|
cert, err := tls.LoadX509KeyPair(tlsInfo.CertFile, tlsInfo.KeyFile)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", err)
|
return nil, fmt.Errorf("error parsing X509 certificate/key pair: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
|
cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("error parsing certificate: %v", err)
|
return nil, fmt.Errorf("error parsing certificate: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create TLSConfig
|
// Create TLSConfig
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
// const (
|
|
||||||
// WorkNum = 4096
|
|
||||||
// )
|
|
||||||
|
|
||||||
var WorkNum int
|
var WorkNum int
|
||||||
|
|
||||||
type Dispatcher struct {
|
type Dispatcher struct {
|
||||||
@@ -31,7 +29,7 @@ func NewDispatcher() *Dispatcher {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (d *Dispatcher) dispatch() {
|
func (d *Dispatcher) dispatch() {
|
||||||
for i := 0; i < MessagePoolNum; i++ {
|
for i := 0; i < (MessagePoolNum + 3); i++ {
|
||||||
go func(idx int) {
|
go func(idx int) {
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
|
|||||||
@@ -1,35 +1,45 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"hmq/packets"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
simplejson "github.com/bitly/go-simplejson"
|
simplejson "github.com/bitly/go-simplejson"
|
||||||
log "github.com/cihub/seelog"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func (c *client) SendInfo() {
|
func (c *client) SendInfo() {
|
||||||
|
if c.status == Disconnected {
|
||||||
|
return
|
||||||
|
}
|
||||||
url := c.info.localIP + ":" + c.broker.config.Cluster.Port
|
url := c.info.localIP + ":" + c.broker.config.Cluster.Port
|
||||||
|
|
||||||
infoMsg := NewInfo(c.broker.id, url, false)
|
infoMsg := NewInfo(c.broker.id, url, false)
|
||||||
err := c.WriterPacket(infoMsg)
|
err := c.WriterPacket(infoMsg)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send info message error, ", err)
|
log.Error("send info message error, ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// log.Info("send info success")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) StartPing() {
|
func (c *client) StartPing() {
|
||||||
timeTicker := time.NewTicker(time.Second * 30)
|
timeTicker := time.NewTicker(time.Second * 50)
|
||||||
ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket)
|
ping := packets.NewControlPacket(packets.Pingreq).(*packets.PingreqPacket)
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-timeTicker.C:
|
case <-timeTicker.C:
|
||||||
err := c.WriterPacket(ping)
|
err := c.WriterPacket(ping)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("ping error: ", err)
|
log.Error("ping error: ", zap.Error(err))
|
||||||
|
c.Close()
|
||||||
|
}
|
||||||
|
case _, ok := <-c.closed:
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -37,6 +47,9 @@ func (c *client) StartPing() {
|
|||||||
|
|
||||||
func (c *client) SendConnect() {
|
func (c *client) SendConnect() {
|
||||||
|
|
||||||
|
if c.status != Connected {
|
||||||
|
return
|
||||||
|
}
|
||||||
m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket)
|
m := packets.NewControlPacket(packets.Connect).(*packets.ConnectPacket)
|
||||||
|
|
||||||
m.CleanSession = true
|
m.CleanSession = true
|
||||||
@@ -44,10 +57,10 @@ func (c *client) SendConnect() {
|
|||||||
m.Keepalive = uint16(60)
|
m.Keepalive = uint16(60)
|
||||||
err := c.WriterPacket(m)
|
err := c.WriterPacket(m)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("send connect message error, ", err)
|
log.Error("send connect message error, ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// log.Info("send connet success")
|
log.Info("send connect success")
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInfo(sid, url string, isforword bool) *packets.PublishPacket {
|
func NewInfo(sid, url string, isforword bool) *packets.PublishPacket {
|
||||||
@@ -55,7 +68,7 @@ func NewInfo(sid, url string, isforword bool) *packets.PublishPacket {
|
|||||||
pub.Qos = 0
|
pub.Qos = 0
|
||||||
pub.TopicName = BrokerInfoTopic
|
pub.TopicName = BrokerInfoTopic
|
||||||
pub.Retain = false
|
pub.Retain = false
|
||||||
info := fmt.Sprintf(`{"remoteID":"%s","url":"%s","isForward":%t}`, sid, url, isforword)
|
info := fmt.Sprintf(`{"brokerID":"%s","brokerUrl":"%s"}`, sid, url)
|
||||||
// log.Info("new info", string(info))
|
// log.Info("new info", string(info))
|
||||||
pub.Payload = []byte(info)
|
pub.Payload = []byte(info)
|
||||||
return pub
|
return pub
|
||||||
@@ -68,47 +81,36 @@ func (c *client) ProcessInfo(packet *packets.PublishPacket) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("recv remoteInfo: ", string(packet.Payload))
|
log.Info("recv remoteInfo: ", zap.String("payload", string(packet.Payload)))
|
||||||
|
|
||||||
js, e := simplejson.NewJson(packet.Payload)
|
js, err := simplejson.NewJson(packet.Payload)
|
||||||
if e != nil {
|
if err != nil {
|
||||||
log.Warn("parse info message err", e)
|
log.Warn("parse info message err", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
rid := js.Get("remoteID").MustString()
|
routes, err := js.Get("data").Map()
|
||||||
rurl := js.Get("url").MustString()
|
if routes == nil {
|
||||||
isForward := js.Get("isForward").MustBool()
|
log.Error("receive info message error, ", zap.Error(err))
|
||||||
|
|
||||||
if rid == "" {
|
|
||||||
log.Error("receive info message error with remoteID is null")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if rid == b.id {
|
b.nodes = routes
|
||||||
if !isForward {
|
|
||||||
c.Close() //close connet self
|
b.mu.Lock()
|
||||||
|
for rid, rurl := range routes {
|
||||||
|
if rid == b.id {
|
||||||
|
continue
|
||||||
}
|
}
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
exist := b.CheckRemoteExist(rid, rurl)
|
url, ok := rurl.(string)
|
||||||
if !exist {
|
if ok {
|
||||||
go b.connectRouter(rurl, rid)
|
exist := b.CheckRemoteExist(rid, url)
|
||||||
}
|
if !exist {
|
||||||
// log.Info("isforword: ", isForward)
|
b.connectRouter(rid, url)
|
||||||
if !isForward {
|
}
|
||||||
route := &route{
|
|
||||||
remoteUrl: rurl,
|
|
||||||
remoteID: rid,
|
|
||||||
}
|
}
|
||||||
c.route = route
|
|
||||||
|
|
||||||
go b.SendLocalSubsToRouter(c)
|
|
||||||
// log.Info("BroadcastInfoMessage starting... ")
|
|
||||||
infoMsg := NewInfo(rid, rurl, true)
|
|
||||||
b.BroadcastInfoMessage(rid, infoMsg)
|
|
||||||
}
|
}
|
||||||
|
b.mu.Unlock()
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hmq/packets"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -29,8 +32,8 @@ type MessagePool struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func InitMessagePool() {
|
func InitMessagePool() {
|
||||||
MSGPool = make([]MessagePool, (MessagePoolNum + 2))
|
MSGPool = make([]MessagePool, (MessagePoolNum + 3))
|
||||||
for i := 0; i < (MessagePoolNum + 2); i++ {
|
for i := 0; i < (MessagePoolNum + 3); i++ {
|
||||||
MSGPool[i].Init(MessagePoolUser, MessagePoolMessageNum)
|
MSGPool[i].Init(MessagePoolUser, MessagePoolMessageNum)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hmq/packets"
|
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
)
|
)
|
||||||
|
|
||||||
type RetainList struct {
|
type RetainList struct {
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
// A result structure better optimized for queue subs.
|
// A result structure better optimized for queue subs.
|
||||||
@@ -209,7 +211,7 @@ func (s *Sublist) Match(topic string) *SublistResult {
|
|||||||
|
|
||||||
tokens, err := PublishTopicCheckAndSpilt(topic)
|
tokens, err := PublishTopicCheckAndSpilt(topic)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("\tserver/sublist.go: ", err)
|
log.Error("\tserver/sublist.go: ", zap.Error(err))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -241,7 +243,6 @@ func (s *Sublist) Match(topic string) *SublistResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
s.Unlock()
|
s.Unlock()
|
||||||
// log.Info("SublistResult: ", result)
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -294,7 +295,6 @@ func removeSubFromList(sub *subscription, sl []*subscription) ([]*subscription,
|
|||||||
sl[i] = sl[last]
|
sl[i] = sl[last]
|
||||||
sl[last] = nil
|
sl[last] = nil
|
||||||
sl = sl[:last]
|
sl = sl[:last]
|
||||||
// log.Info("removeSubFromList success")
|
|
||||||
return shrinkAsNeeded(sl), true
|
return shrinkAsNeeded(sl), true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
type Worker struct {
|
type Worker struct {
|
||||||
|
|||||||
@@ -4,9 +4,9 @@
|
|||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"cluster": {
|
"cluster": {
|
||||||
"host": "0.0.0.0",
|
"host": "0.0.0.0",
|
||||||
"port": "1993",
|
"port": "1993"
|
||||||
"routes": []
|
|
||||||
},
|
},
|
||||||
|
"router": "127.0.0.1:9888",
|
||||||
"tlsPort": "8883",
|
"tlsPort": "8883",
|
||||||
"tlsHost": "0.0.0.0",
|
"tlsHost": "0.0.0.0",
|
||||||
"wsPort": "1888",
|
"wsPort": "1888",
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package acl
|
package acl
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>*/
|
||||||
package acl
|
package acl
|
||||||
|
|
||||||
import "strings"
|
import "strings"
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package acl
|
package acl
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
51
logger/logger.go
Normal file
51
logger/logger.go
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
|
|
||||||
|
package logger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// env can be setup at build time with Go Linker. Value could be prod or whatever else for dev env
|
||||||
|
env string
|
||||||
|
instance *zap.Logger
|
||||||
|
logCfg zap.Config
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewDevLogger return a logger for dev builds
|
||||||
|
func NewDevLogger() (*zap.Logger, error) {
|
||||||
|
logCfg := zap.NewDevelopmentConfig()
|
||||||
|
return logCfg.Build()
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewProdLogger return a logger for production builds
|
||||||
|
func NewProdLogger() (*zap.Logger, error) {
|
||||||
|
logCfg := zap.NewProductionConfig()
|
||||||
|
logCfg.DisableStacktrace = true
|
||||||
|
logCfg.Level = zap.NewAtomicLevelAt(zap.InfoLevel)
|
||||||
|
return logCfg.Build()
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
var err error
|
||||||
|
var log *zap.Logger
|
||||||
|
if env == "prod" {
|
||||||
|
log, err = NewProdLogger()
|
||||||
|
} else {
|
||||||
|
log, err = NewDevLogger()
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
panic("Unable to create a logger.")
|
||||||
|
}
|
||||||
|
defer log.Sync()
|
||||||
|
|
||||||
|
log.Debug("Logger initialization succeeded")
|
||||||
|
instance = log.Named("hmq")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get return a *zap.Logger instance
|
||||||
|
func Get() *zap.Logger {
|
||||||
|
return instance
|
||||||
|
}
|
||||||
33
logger/logger_test.go
Normal file
33
logger/logger_test.go
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
|
package logger
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGet(t *testing.T) {
|
||||||
|
var l *zap.Logger
|
||||||
|
logger := Get()
|
||||||
|
|
||||||
|
assert.NotNil(t, logger)
|
||||||
|
assert.IsType(t, l, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewDevLogger(t *testing.T) {
|
||||||
|
logger, err := NewDevLogger()
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.True(t, logger.Core().Enabled(zap.DebugLevel))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewProdLogger(t *testing.T) {
|
||||||
|
logger, err := NewProdLogger()
|
||||||
|
|
||||||
|
assert.Nil(t, err)
|
||||||
|
assert.False(t, logger.Core().Enabled(zap.DebugLevel))
|
||||||
|
}
|
||||||
27
main.go
27
main.go
@@ -1,33 +1,42 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted, provided that the above
|
||||||
|
copyright notice and this permission notice appear in all copies.
|
||||||
|
*/
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"hmq/broker"
|
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/fhmq/hmq/broker"
|
||||||
|
"github.com/fhmq/hmq/logger"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
log = logger.Get().Named("Main")
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||||
runtime.GC()
|
config, err := broker.ConfigureConfig()
|
||||||
config, er := broker.LoadConfig()
|
if err != nil {
|
||||||
if er != nil {
|
log.Error("configure broker config error: ", zap.Error(err))
|
||||||
log.Error("Load Config file error: ", er)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
broker.StartDispatcher()
|
|
||||||
|
|
||||||
b, err := broker.NewBroker(config)
|
b, err := broker.NewBroker(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("New Broker error: ", er)
|
log.Error("New Broker error: ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
b.Start()
|
b.Start()
|
||||||
|
|
||||||
s := waitForSignal()
|
s := waitForSignal()
|
||||||
log.Infof("signal got: %v ,broker closed.", s)
|
log.Info("signal received, broker closed.", zap.Any("signal", s))
|
||||||
}
|
}
|
||||||
|
|
||||||
func waitForSignal() os.Signal {
|
func waitForSignal() os.Signal {
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//ConnackPacket is an internal representation of the fields of the
|
|
||||||
//Connack MQTT packet
|
|
||||||
type ConnackPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
SessionPresent bool
|
|
||||||
ReturnCode byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ca *ConnackPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", ca.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("sessionpresent: %t returncode: %d", ca.SessionPresent, ca.ReturnCode)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ca *ConnackPacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
body.WriteByte(boolToByte(ca.SessionPresent))
|
|
||||||
body.WriteByte(ca.ReturnCode)
|
|
||||||
ca.FixedHeader.RemainingLength = 2
|
|
||||||
packet := ca.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (ca *ConnackPacket) Unpack(b io.Reader) error {
|
|
||||||
ca.SessionPresent = 1&decodeByte(b) > 0
|
|
||||||
ca.ReturnCode = decodeByte(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (ca *ConnackPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: 0}
|
|
||||||
}
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//ConnectPacket is an internal representation of the fields of the
|
|
||||||
//Connect MQTT packet
|
|
||||||
type ConnectPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
ProtocolName string
|
|
||||||
ProtocolVersion byte
|
|
||||||
CleanSession bool
|
|
||||||
WillFlag bool
|
|
||||||
WillQos byte
|
|
||||||
WillRetain bool
|
|
||||||
UsernameFlag bool
|
|
||||||
PasswordFlag bool
|
|
||||||
ReservedBit byte
|
|
||||||
Keepalive uint16
|
|
||||||
|
|
||||||
ClientIdentifier string
|
|
||||||
WillTopic string
|
|
||||||
WillMessage []byte
|
|
||||||
Username string
|
|
||||||
Password []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *ConnectPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", c.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("protocolversion: %d protocolname: %s cleansession: %t willflag: %t WillQos: %d WillRetain: %t Usernameflag: %t Passwordflag: %t keepalive: %d clientId: %s willtopic: %s willmessage: %s Username: %s Password: %s", c.ProtocolVersion, c.ProtocolName, c.CleanSession, c.WillFlag, c.WillQos, c.WillRetain, c.UsernameFlag, c.PasswordFlag, c.Keepalive, c.ClientIdentifier, c.WillTopic, c.WillMessage, c.Username, c.Password)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *ConnectPacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
body.Write(encodeString(c.ProtocolName))
|
|
||||||
body.WriteByte(c.ProtocolVersion)
|
|
||||||
body.WriteByte(boolToByte(c.CleanSession)<<1 | boolToByte(c.WillFlag)<<2 | c.WillQos<<3 | boolToByte(c.WillRetain)<<5 | boolToByte(c.PasswordFlag)<<6 | boolToByte(c.UsernameFlag)<<7)
|
|
||||||
body.Write(encodeUint16(c.Keepalive))
|
|
||||||
body.Write(encodeString(c.ClientIdentifier))
|
|
||||||
if c.WillFlag {
|
|
||||||
body.Write(encodeString(c.WillTopic))
|
|
||||||
body.Write(encodeBytes(c.WillMessage))
|
|
||||||
}
|
|
||||||
if c.UsernameFlag {
|
|
||||||
body.Write(encodeString(c.Username))
|
|
||||||
}
|
|
||||||
if c.PasswordFlag {
|
|
||||||
body.Write(encodeBytes(c.Password))
|
|
||||||
}
|
|
||||||
c.FixedHeader.RemainingLength = body.Len()
|
|
||||||
packet := c.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (c *ConnectPacket) Unpack(b io.Reader) error {
|
|
||||||
c.ProtocolName = decodeString(b)
|
|
||||||
c.ProtocolVersion = decodeByte(b)
|
|
||||||
options := decodeByte(b)
|
|
||||||
c.ReservedBit = 1 & options
|
|
||||||
c.CleanSession = 1&(options>>1) > 0
|
|
||||||
c.WillFlag = 1&(options>>2) > 0
|
|
||||||
c.WillQos = 3 & (options >> 3)
|
|
||||||
c.WillRetain = 1&(options>>5) > 0
|
|
||||||
c.PasswordFlag = 1&(options>>6) > 0
|
|
||||||
c.UsernameFlag = 1&(options>>7) > 0
|
|
||||||
c.Keepalive = decodeUint16(b)
|
|
||||||
c.ClientIdentifier = decodeString(b)
|
|
||||||
if c.WillFlag {
|
|
||||||
c.WillTopic = decodeString(b)
|
|
||||||
c.WillMessage = decodeBytes(b)
|
|
||||||
}
|
|
||||||
if c.UsernameFlag {
|
|
||||||
c.Username = decodeString(b)
|
|
||||||
}
|
|
||||||
if c.PasswordFlag {
|
|
||||||
c.Password = decodeBytes(b)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Validate performs validation of the fields of a Connect packet
|
|
||||||
func (c *ConnectPacket) Validate() byte {
|
|
||||||
if c.PasswordFlag && !c.UsernameFlag {
|
|
||||||
return ErrRefusedBadUsernameOrPassword
|
|
||||||
}
|
|
||||||
if c.ReservedBit != 0 {
|
|
||||||
//Bad reserved bit
|
|
||||||
return ErrProtocolViolation
|
|
||||||
}
|
|
||||||
if (c.ProtocolName == "MQIsdp" && c.ProtocolVersion != 3) || (c.ProtocolName == "MQTT" && c.ProtocolVersion != 4) {
|
|
||||||
//Mismatched or unsupported protocol version
|
|
||||||
return ErrRefusedBadProtocolVersion
|
|
||||||
}
|
|
||||||
if c.ProtocolName != "MQIsdp" && c.ProtocolName != "MQTT" {
|
|
||||||
//Bad protocol name
|
|
||||||
return ErrProtocolViolation
|
|
||||||
}
|
|
||||||
if len(c.ClientIdentifier) > 65535 || len(c.Username) > 65535 || len(c.Password) > 65535 {
|
|
||||||
//Bad size field
|
|
||||||
return ErrProtocolViolation
|
|
||||||
}
|
|
||||||
if len(c.ClientIdentifier) == 0 && !c.CleanSession {
|
|
||||||
//Bad client identifier
|
|
||||||
return ErrRefusedIDRejected
|
|
||||||
}
|
|
||||||
return Accepted
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (c *ConnectPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: 0}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//DisconnectPacket is an internal representation of the fields of the
|
|
||||||
//Disconnect MQTT packet
|
|
||||||
type DisconnectPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DisconnectPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", d.FixedHeader)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DisconnectPacket) Write(w io.Writer) error {
|
|
||||||
packet := d.FixedHeader.pack()
|
|
||||||
_, err := packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (d *DisconnectPacket) Unpack(b io.Reader) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (d *DisconnectPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: 0}
|
|
||||||
}
|
|
||||||
@@ -1,322 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//ControlPacket defines the interface for structs intended to hold
|
|
||||||
//decoded MQTT packets, either from being read or before being
|
|
||||||
//written
|
|
||||||
type ControlPacket interface {
|
|
||||||
Write(io.Writer) error
|
|
||||||
Unpack(io.Reader) error
|
|
||||||
String() string
|
|
||||||
Details() Details
|
|
||||||
}
|
|
||||||
|
|
||||||
//PacketNames maps the constants for each of the MQTT packet types
|
|
||||||
//to a string representation of their name.
|
|
||||||
var PacketNames = map[uint8]string{
|
|
||||||
1: "CONNECT",
|
|
||||||
2: "CONNACK",
|
|
||||||
3: "PUBLISH",
|
|
||||||
4: "PUBACK",
|
|
||||||
5: "PUBREC",
|
|
||||||
6: "PUBREL",
|
|
||||||
7: "PUBCOMP",
|
|
||||||
8: "SUBSCRIBE",
|
|
||||||
9: "SUBACK",
|
|
||||||
10: "UNSUBSCRIBE",
|
|
||||||
11: "UNSUBACK",
|
|
||||||
12: "PINGREQ",
|
|
||||||
13: "PINGRESP",
|
|
||||||
14: "DISCONNECT",
|
|
||||||
}
|
|
||||||
|
|
||||||
//Below are the constants assigned to each of the MQTT packet types
|
|
||||||
const (
|
|
||||||
Connect = 1
|
|
||||||
Connack = 2
|
|
||||||
Publish = 3
|
|
||||||
Puback = 4
|
|
||||||
Pubrec = 5
|
|
||||||
Pubrel = 6
|
|
||||||
Pubcomp = 7
|
|
||||||
Subscribe = 8
|
|
||||||
Suback = 9
|
|
||||||
Unsubscribe = 10
|
|
||||||
Unsuback = 11
|
|
||||||
Pingreq = 12
|
|
||||||
Pingresp = 13
|
|
||||||
Disconnect = 14
|
|
||||||
)
|
|
||||||
|
|
||||||
//Below are the const definitions for error codes returned by
|
|
||||||
//Connect()
|
|
||||||
const (
|
|
||||||
Accepted = 0x00
|
|
||||||
ErrRefusedBadProtocolVersion = 0x01
|
|
||||||
ErrRefusedIDRejected = 0x02
|
|
||||||
ErrRefusedServerUnavailable = 0x03
|
|
||||||
ErrRefusedBadUsernameOrPassword = 0x04
|
|
||||||
ErrRefusedNotAuthorised = 0x05
|
|
||||||
ErrNetworkError = 0xFE
|
|
||||||
ErrProtocolViolation = 0xFF
|
|
||||||
)
|
|
||||||
|
|
||||||
//ConnackReturnCodes is a map of the error codes constants for Connect()
|
|
||||||
//to a string representation of the error
|
|
||||||
var ConnackReturnCodes = map[uint8]string{
|
|
||||||
0: "Connection Accepted",
|
|
||||||
1: "Connection Refused: Bad Protocol Version",
|
|
||||||
2: "Connection Refused: Client Identifier Rejected",
|
|
||||||
3: "Connection Refused: Server Unavailable",
|
|
||||||
4: "Connection Refused: Username or Password in unknown format",
|
|
||||||
5: "Connection Refused: Not Authorised",
|
|
||||||
254: "Connection Error",
|
|
||||||
255: "Connection Refused: Protocol Violation",
|
|
||||||
}
|
|
||||||
|
|
||||||
//ConnErrors is a map of the errors codes constants for Connect()
|
|
||||||
//to a Go error
|
|
||||||
var ConnErrors = map[byte]error{
|
|
||||||
Accepted: nil,
|
|
||||||
ErrRefusedBadProtocolVersion: errors.New("Unnacceptable protocol version"),
|
|
||||||
ErrRefusedIDRejected: errors.New("Identifier rejected"),
|
|
||||||
ErrRefusedServerUnavailable: errors.New("Server Unavailable"),
|
|
||||||
ErrRefusedBadUsernameOrPassword: errors.New("Bad user name or password"),
|
|
||||||
ErrRefusedNotAuthorised: errors.New("Not Authorized"),
|
|
||||||
ErrNetworkError: errors.New("Network Error"),
|
|
||||||
ErrProtocolViolation: errors.New("Protocol Violation"),
|
|
||||||
}
|
|
||||||
|
|
||||||
//ReadPacket takes an instance of an io.Reader (such as net.Conn) and attempts
|
|
||||||
//to read an MQTT packet from the stream. It returns a ControlPacket
|
|
||||||
//representing the decoded MQTT packet and an error. One of these returns will
|
|
||||||
//always be nil, a nil ControlPacket indicating an error occurred.
|
|
||||||
func ReadPacket(r io.Reader) (cp ControlPacket, err error) {
|
|
||||||
var fh FixedHeader
|
|
||||||
b := make([]byte, 1)
|
|
||||||
|
|
||||||
_, err = io.ReadFull(r, b)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
fh.unpack(b[0], r)
|
|
||||||
cp = NewControlPacketWithHeader(fh)
|
|
||||||
if cp == nil {
|
|
||||||
return nil, errors.New("Bad data from client")
|
|
||||||
}
|
|
||||||
packetBytes := make([]byte, fh.RemainingLength)
|
|
||||||
_, err = io.ReadFull(r, packetBytes)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
err = cp.Unpack(bytes.NewBuffer(packetBytes))
|
|
||||||
return cp, err
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewControlPacket is used to create a new ControlPacket of the type specified
|
|
||||||
//by packetType, this is usually done by reference to the packet type constants
|
|
||||||
//defined in packets.go. The newly created ControlPacket is empty and a pointer
|
|
||||||
//is returned.
|
|
||||||
func NewControlPacket(packetType byte) (cp ControlPacket) {
|
|
||||||
switch packetType {
|
|
||||||
case Connect:
|
|
||||||
cp = &ConnectPacket{FixedHeader: FixedHeader{MessageType: Connect}}
|
|
||||||
case Connack:
|
|
||||||
cp = &ConnackPacket{FixedHeader: FixedHeader{MessageType: Connack}}
|
|
||||||
case Disconnect:
|
|
||||||
cp = &DisconnectPacket{FixedHeader: FixedHeader{MessageType: Disconnect}}
|
|
||||||
case Publish:
|
|
||||||
cp = &PublishPacket{FixedHeader: FixedHeader{MessageType: Publish}}
|
|
||||||
case Puback:
|
|
||||||
cp = &PubackPacket{FixedHeader: FixedHeader{MessageType: Puback}}
|
|
||||||
case Pubrec:
|
|
||||||
cp = &PubrecPacket{FixedHeader: FixedHeader{MessageType: Pubrec}}
|
|
||||||
case Pubrel:
|
|
||||||
cp = &PubrelPacket{FixedHeader: FixedHeader{MessageType: Pubrel, Qos: 1}}
|
|
||||||
case Pubcomp:
|
|
||||||
cp = &PubcompPacket{FixedHeader: FixedHeader{MessageType: Pubcomp}}
|
|
||||||
case Subscribe:
|
|
||||||
cp = &SubscribePacket{FixedHeader: FixedHeader{MessageType: Subscribe, Qos: 1}}
|
|
||||||
case Suback:
|
|
||||||
cp = &SubackPacket{FixedHeader: FixedHeader{MessageType: Suback}}
|
|
||||||
case Unsubscribe:
|
|
||||||
cp = &UnsubscribePacket{FixedHeader: FixedHeader{MessageType: Unsubscribe, Qos: 1}}
|
|
||||||
case Unsuback:
|
|
||||||
cp = &UnsubackPacket{FixedHeader: FixedHeader{MessageType: Unsuback}}
|
|
||||||
case Pingreq:
|
|
||||||
cp = &PingreqPacket{FixedHeader: FixedHeader{MessageType: Pingreq}}
|
|
||||||
case Pingresp:
|
|
||||||
cp = &PingrespPacket{FixedHeader: FixedHeader{MessageType: Pingresp}}
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return cp
|
|
||||||
}
|
|
||||||
|
|
||||||
//NewControlPacketWithHeader is used to create a new ControlPacket of the type
|
|
||||||
//specified within the FixedHeader that is passed to the function.
|
|
||||||
//The newly created ControlPacket is empty and a pointer is returned.
|
|
||||||
func NewControlPacketWithHeader(fh FixedHeader) (cp ControlPacket) {
|
|
||||||
switch fh.MessageType {
|
|
||||||
case Connect:
|
|
||||||
cp = &ConnectPacket{FixedHeader: fh}
|
|
||||||
case Connack:
|
|
||||||
cp = &ConnackPacket{FixedHeader: fh}
|
|
||||||
case Disconnect:
|
|
||||||
cp = &DisconnectPacket{FixedHeader: fh}
|
|
||||||
case Publish:
|
|
||||||
cp = &PublishPacket{FixedHeader: fh}
|
|
||||||
case Puback:
|
|
||||||
cp = &PubackPacket{FixedHeader: fh}
|
|
||||||
case Pubrec:
|
|
||||||
cp = &PubrecPacket{FixedHeader: fh}
|
|
||||||
case Pubrel:
|
|
||||||
cp = &PubrelPacket{FixedHeader: fh}
|
|
||||||
case Pubcomp:
|
|
||||||
cp = &PubcompPacket{FixedHeader: fh}
|
|
||||||
case Subscribe:
|
|
||||||
cp = &SubscribePacket{FixedHeader: fh}
|
|
||||||
case Suback:
|
|
||||||
cp = &SubackPacket{FixedHeader: fh}
|
|
||||||
case Unsubscribe:
|
|
||||||
cp = &UnsubscribePacket{FixedHeader: fh}
|
|
||||||
case Unsuback:
|
|
||||||
cp = &UnsubackPacket{FixedHeader: fh}
|
|
||||||
case Pingreq:
|
|
||||||
cp = &PingreqPacket{FixedHeader: fh}
|
|
||||||
case Pingresp:
|
|
||||||
cp = &PingrespPacket{FixedHeader: fh}
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return cp
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details struct returned by the Details() function called on
|
|
||||||
//ControlPackets to present details of the Qos and MessageID
|
|
||||||
//of the ControlPacket
|
|
||||||
type Details struct {
|
|
||||||
Qos byte
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
//FixedHeader is a struct to hold the decoded information from
|
|
||||||
//the fixed header of an MQTT ControlPacket
|
|
||||||
type FixedHeader struct {
|
|
||||||
MessageType byte
|
|
||||||
Dup bool
|
|
||||||
Qos byte
|
|
||||||
Retain bool
|
|
||||||
RemainingLength int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fh FixedHeader) String() string {
|
|
||||||
return fmt.Sprintf("%s: dup: %t qos: %d retain: %t rLength: %d", PacketNames[fh.MessageType], fh.Dup, fh.Qos, fh.Retain, fh.RemainingLength)
|
|
||||||
}
|
|
||||||
|
|
||||||
func boolToByte(b bool) byte {
|
|
||||||
switch b {
|
|
||||||
case true:
|
|
||||||
return 1
|
|
||||||
default:
|
|
||||||
return 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fh *FixedHeader) pack() bytes.Buffer {
|
|
||||||
var header bytes.Buffer
|
|
||||||
header.WriteByte(fh.MessageType<<4 | boolToByte(fh.Dup)<<3 | fh.Qos<<1 | boolToByte(fh.Retain))
|
|
||||||
header.Write(encodeLength(fh.RemainingLength))
|
|
||||||
return header
|
|
||||||
}
|
|
||||||
|
|
||||||
func (fh *FixedHeader) unpack(typeAndFlags byte, r io.Reader) {
|
|
||||||
fh.MessageType = typeAndFlags >> 4
|
|
||||||
fh.Dup = (typeAndFlags>>3)&0x01 > 0
|
|
||||||
fh.Qos = (typeAndFlags >> 1) & 0x03
|
|
||||||
fh.Retain = typeAndFlags&0x01 > 0
|
|
||||||
fh.RemainingLength = decodeLength(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeByte(b io.Reader) byte {
|
|
||||||
num := make([]byte, 1)
|
|
||||||
b.Read(num)
|
|
||||||
return num[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeUint16(b io.Reader) uint16 {
|
|
||||||
num := make([]byte, 2)
|
|
||||||
b.Read(num)
|
|
||||||
return binary.BigEndian.Uint16(num)
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeUint16(num uint16) []byte {
|
|
||||||
bytes := make([]byte, 2)
|
|
||||||
binary.BigEndian.PutUint16(bytes, num)
|
|
||||||
return bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeString(field string) []byte {
|
|
||||||
fieldLength := make([]byte, 2)
|
|
||||||
binary.BigEndian.PutUint16(fieldLength, uint16(len(field)))
|
|
||||||
return append(fieldLength, []byte(field)...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeString(b io.Reader) string {
|
|
||||||
fieldLength := decodeUint16(b)
|
|
||||||
field := make([]byte, fieldLength)
|
|
||||||
b.Read(field)
|
|
||||||
return string(field)
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeBytes(b io.Reader) []byte {
|
|
||||||
fieldLength := decodeUint16(b)
|
|
||||||
field := make([]byte, fieldLength)
|
|
||||||
b.Read(field)
|
|
||||||
return field
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeBytes(field []byte) []byte {
|
|
||||||
fieldLength := make([]byte, 2)
|
|
||||||
binary.BigEndian.PutUint16(fieldLength, uint16(len(field)))
|
|
||||||
return append(fieldLength, field...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func encodeLength(length int) []byte {
|
|
||||||
var encLength []byte
|
|
||||||
for {
|
|
||||||
digit := byte(length % 128)
|
|
||||||
length /= 128
|
|
||||||
if length > 0 {
|
|
||||||
digit |= 0x80
|
|
||||||
}
|
|
||||||
encLength = append(encLength, digit)
|
|
||||||
if length == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return encLength
|
|
||||||
}
|
|
||||||
|
|
||||||
func decodeLength(r io.Reader) int {
|
|
||||||
var rLength uint32
|
|
||||||
var multiplier uint32
|
|
||||||
b := make([]byte, 1)
|
|
||||||
for multiplier < 27 { //fix: Infinite '(digit & 128) == 1' will cause the dead loop
|
|
||||||
io.ReadFull(r, b)
|
|
||||||
digit := b[0]
|
|
||||||
rLength |= uint32(digit&127) << multiplier
|
|
||||||
if (digit & 128) == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
multiplier += 7
|
|
||||||
}
|
|
||||||
return int(rLength)
|
|
||||||
}
|
|
||||||
@@ -1,159 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestPacketNames(t *testing.T) {
|
|
||||||
if PacketNames[1] != "CONNECT" {
|
|
||||||
t.Errorf("PacketNames[1] is %s, should be %s", PacketNames[1], "CONNECT")
|
|
||||||
}
|
|
||||||
if PacketNames[2] != "CONNACK" {
|
|
||||||
t.Errorf("PacketNames[2] is %s, should be %s", PacketNames[2], "CONNACK")
|
|
||||||
}
|
|
||||||
if PacketNames[3] != "PUBLISH" {
|
|
||||||
t.Errorf("PacketNames[3] is %s, should be %s", PacketNames[3], "PUBLISH")
|
|
||||||
}
|
|
||||||
if PacketNames[4] != "PUBACK" {
|
|
||||||
t.Errorf("PacketNames[4] is %s, should be %s", PacketNames[4], "PUBACK")
|
|
||||||
}
|
|
||||||
if PacketNames[5] != "PUBREC" {
|
|
||||||
t.Errorf("PacketNames[5] is %s, should be %s", PacketNames[5], "PUBREC")
|
|
||||||
}
|
|
||||||
if PacketNames[6] != "PUBREL" {
|
|
||||||
t.Errorf("PacketNames[6] is %s, should be %s", PacketNames[6], "PUBREL")
|
|
||||||
}
|
|
||||||
if PacketNames[7] != "PUBCOMP" {
|
|
||||||
t.Errorf("PacketNames[7] is %s, should be %s", PacketNames[7], "PUBCOMP")
|
|
||||||
}
|
|
||||||
if PacketNames[8] != "SUBSCRIBE" {
|
|
||||||
t.Errorf("PacketNames[8] is %s, should be %s", PacketNames[8], "SUBSCRIBE")
|
|
||||||
}
|
|
||||||
if PacketNames[9] != "SUBACK" {
|
|
||||||
t.Errorf("PacketNames[9] is %s, should be %s", PacketNames[9], "SUBACK")
|
|
||||||
}
|
|
||||||
if PacketNames[10] != "UNSUBSCRIBE" {
|
|
||||||
t.Errorf("PacketNames[10] is %s, should be %s", PacketNames[10], "UNSUBSCRIBE")
|
|
||||||
}
|
|
||||||
if PacketNames[11] != "UNSUBACK" {
|
|
||||||
t.Errorf("PacketNames[11] is %s, should be %s", PacketNames[11], "UNSUBACK")
|
|
||||||
}
|
|
||||||
if PacketNames[12] != "PINGREQ" {
|
|
||||||
t.Errorf("PacketNames[12] is %s, should be %s", PacketNames[12], "PINGREQ")
|
|
||||||
}
|
|
||||||
if PacketNames[13] != "PINGRESP" {
|
|
||||||
t.Errorf("PacketNames[13] is %s, should be %s", PacketNames[13], "PINGRESP")
|
|
||||||
}
|
|
||||||
if PacketNames[14] != "DISCONNECT" {
|
|
||||||
t.Errorf("PacketNames[14] is %s, should be %s", PacketNames[14], "DISCONNECT")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestPacketConsts(t *testing.T) {
|
|
||||||
if Connect != 1 {
|
|
||||||
t.Errorf("Const for Connect is %d, should be %d", Connect, 1)
|
|
||||||
}
|
|
||||||
if Connack != 2 {
|
|
||||||
t.Errorf("Const for Connack is %d, should be %d", Connack, 2)
|
|
||||||
}
|
|
||||||
if Publish != 3 {
|
|
||||||
t.Errorf("Const for Publish is %d, should be %d", Publish, 3)
|
|
||||||
}
|
|
||||||
if Puback != 4 {
|
|
||||||
t.Errorf("Const for Puback is %d, should be %d", Puback, 4)
|
|
||||||
}
|
|
||||||
if Pubrec != 5 {
|
|
||||||
t.Errorf("Const for Pubrec is %d, should be %d", Pubrec, 5)
|
|
||||||
}
|
|
||||||
if Pubrel != 6 {
|
|
||||||
t.Errorf("Const for Pubrel is %d, should be %d", Pubrel, 6)
|
|
||||||
}
|
|
||||||
if Pubcomp != 7 {
|
|
||||||
t.Errorf("Const for Pubcomp is %d, should be %d", Pubcomp, 7)
|
|
||||||
}
|
|
||||||
if Subscribe != 8 {
|
|
||||||
t.Errorf("Const for Subscribe is %d, should be %d", Subscribe, 8)
|
|
||||||
}
|
|
||||||
if Suback != 9 {
|
|
||||||
t.Errorf("Const for Suback is %d, should be %d", Suback, 9)
|
|
||||||
}
|
|
||||||
if Unsubscribe != 10 {
|
|
||||||
t.Errorf("Const for Unsubscribe is %d, should be %d", Unsubscribe, 10)
|
|
||||||
}
|
|
||||||
if Unsuback != 11 {
|
|
||||||
t.Errorf("Const for Unsuback is %d, should be %d", Unsuback, 11)
|
|
||||||
}
|
|
||||||
if Pingreq != 12 {
|
|
||||||
t.Errorf("Const for Pingreq is %d, should be %d", Pingreq, 12)
|
|
||||||
}
|
|
||||||
if Pingresp != 13 {
|
|
||||||
t.Errorf("Const for Pingresp is %d, should be %d", Pingresp, 13)
|
|
||||||
}
|
|
||||||
if Disconnect != 14 {
|
|
||||||
t.Errorf("Const for Disconnect is %d, should be %d", Disconnect, 14)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConnackConsts(t *testing.T) {
|
|
||||||
if Accepted != 0x00 {
|
|
||||||
t.Errorf("Const for Accepted is %d, should be %d", Accepted, 0)
|
|
||||||
}
|
|
||||||
if ErrRefusedBadProtocolVersion != 0x01 {
|
|
||||||
t.Errorf("Const for RefusedBadProtocolVersion is %d, should be %d", ErrRefusedBadProtocolVersion, 1)
|
|
||||||
}
|
|
||||||
if ErrRefusedIDRejected != 0x02 {
|
|
||||||
t.Errorf("Const for RefusedIDRejected is %d, should be %d", ErrRefusedIDRejected, 2)
|
|
||||||
}
|
|
||||||
if ErrRefusedServerUnavailable != 0x03 {
|
|
||||||
t.Errorf("Const for RefusedServerUnavailable is %d, should be %d", ErrRefusedServerUnavailable, 3)
|
|
||||||
}
|
|
||||||
if ErrRefusedBadUsernameOrPassword != 0x04 {
|
|
||||||
t.Errorf("Const for RefusedBadUsernameOrPassword is %d, should be %d", ErrRefusedBadUsernameOrPassword, 4)
|
|
||||||
}
|
|
||||||
if ErrRefusedNotAuthorised != 0x05 {
|
|
||||||
t.Errorf("Const for RefusedNotAuthorised is %d, should be %d", ErrRefusedNotAuthorised, 5)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConnectPacket(t *testing.T) {
|
|
||||||
connectPacketBytes := bytes.NewBuffer([]byte{16, 52, 0, 4, 77, 81, 84, 84, 4, 204, 0, 0, 0, 0, 0, 4, 116, 101, 115, 116, 0, 12, 84, 101, 115, 116, 32, 80, 97, 121, 108, 111, 97, 100, 0, 8, 116, 101, 115, 116, 117, 115, 101, 114, 0, 8, 116, 101, 115, 116, 112, 97, 115, 115})
|
|
||||||
packet, err := ReadPacket(connectPacketBytes)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("Error reading packet: %s", err.Error())
|
|
||||||
}
|
|
||||||
cp := packet.(*ConnectPacket)
|
|
||||||
if cp.ProtocolName != "MQTT" {
|
|
||||||
t.Errorf("Connect Packet ProtocolName is %s, should be %s", cp.ProtocolName, "MQTT")
|
|
||||||
}
|
|
||||||
if cp.ProtocolVersion != 4 {
|
|
||||||
t.Errorf("Connect Packet ProtocolVersion is %d, should be %d", cp.ProtocolVersion, 4)
|
|
||||||
}
|
|
||||||
if cp.UsernameFlag != true {
|
|
||||||
t.Errorf("Connect Packet UsernameFlag is %t, should be %t", cp.UsernameFlag, true)
|
|
||||||
}
|
|
||||||
if cp.Username != "testuser" {
|
|
||||||
t.Errorf("Connect Packet Username is %s, should be %s", cp.Username, "testuser")
|
|
||||||
}
|
|
||||||
if cp.PasswordFlag != true {
|
|
||||||
t.Errorf("Connect Packet PasswordFlag is %t, should be %t", cp.PasswordFlag, true)
|
|
||||||
}
|
|
||||||
if string(cp.Password) != "testpass" {
|
|
||||||
t.Errorf("Connect Packet Password is %s, should be %s", string(cp.Password), "testpass")
|
|
||||||
}
|
|
||||||
if cp.WillFlag != true {
|
|
||||||
t.Errorf("Connect Packet WillFlag is %t, should be %t", cp.WillFlag, true)
|
|
||||||
}
|
|
||||||
if cp.WillTopic != "test" {
|
|
||||||
t.Errorf("Connect Packet WillTopic is %s, should be %s", cp.WillTopic, "test")
|
|
||||||
}
|
|
||||||
if cp.WillQos != 1 {
|
|
||||||
t.Errorf("Connect Packet WillQos is %d, should be %d", cp.WillQos, 1)
|
|
||||||
}
|
|
||||||
if cp.WillRetain != false {
|
|
||||||
t.Errorf("Connect Packet WillRetain is %t, should be %t", cp.WillRetain, false)
|
|
||||||
}
|
|
||||||
if string(cp.WillMessage) != "Test Payload" {
|
|
||||||
t.Errorf("Connect Packet WillMessage is %s, should be %s", string(cp.WillMessage), "Test Payload")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PingreqPacket is an internal representation of the fields of the
|
|
||||||
//Pingreq MQTT packet
|
|
||||||
type PingreqPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PingreqPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PingreqPacket) Write(w io.Writer) error {
|
|
||||||
packet := pr.FixedHeader.pack()
|
|
||||||
_, err := packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pr *PingreqPacket) Unpack(b io.Reader) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pr *PingreqPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: 0}
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PingrespPacket is an internal representation of the fields of the
|
|
||||||
//Pingresp MQTT packet
|
|
||||||
type PingrespPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PingrespPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PingrespPacket) Write(w io.Writer) error {
|
|
||||||
packet := pr.FixedHeader.pack()
|
|
||||||
_, err := packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pr *PingrespPacket) Unpack(b io.Reader) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pr *PingrespPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: 0}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PubackPacket is an internal representation of the fields of the
|
|
||||||
//Puback MQTT packet
|
|
||||||
type PubackPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pa *PubackPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pa.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pa *PubackPacket) Write(w io.Writer) error {
|
|
||||||
var err error
|
|
||||||
pa.FixedHeader.RemainingLength = 2
|
|
||||||
packet := pa.FixedHeader.pack()
|
|
||||||
packet.Write(encodeUint16(pa.MessageID))
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pa *PubackPacket) Unpack(b io.Reader) error {
|
|
||||||
pa.MessageID = decodeUint16(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pa *PubackPacket) Details() Details {
|
|
||||||
return Details{Qos: pa.Qos, MessageID: pa.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PubcompPacket is an internal representation of the fields of the
|
|
||||||
//Pubcomp MQTT packet
|
|
||||||
type PubcompPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *PubcompPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pc.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pc.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pc *PubcompPacket) Write(w io.Writer) error {
|
|
||||||
var err error
|
|
||||||
pc.FixedHeader.RemainingLength = 2
|
|
||||||
packet := pc.FixedHeader.pack()
|
|
||||||
packet.Write(encodeUint16(pc.MessageID))
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pc *PubcompPacket) Unpack(b io.Reader) error {
|
|
||||||
pc.MessageID = decodeUint16(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pc *PubcompPacket) Details() Details {
|
|
||||||
return Details{Qos: pc.Qos, MessageID: pc.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PublishPacket is an internal representation of the fields of the
|
|
||||||
//Publish MQTT packet
|
|
||||||
type PublishPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
TopicName string
|
|
||||||
MessageID uint16
|
|
||||||
Payload []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PublishPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", p.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("topicName: %s MessageID: %d", p.TopicName, p.MessageID)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("payload: %s", string(p.Payload))
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *PublishPacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
body.Write(encodeString(p.TopicName))
|
|
||||||
if p.Qos > 0 {
|
|
||||||
body.Write(encodeUint16(p.MessageID))
|
|
||||||
}
|
|
||||||
p.FixedHeader.RemainingLength = body.Len() + len(p.Payload)
|
|
||||||
packet := p.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
packet.Write(p.Payload)
|
|
||||||
_, err = w.Write(packet.Bytes())
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (p *PublishPacket) Unpack(b io.Reader) error {
|
|
||||||
var payloadLength = p.FixedHeader.RemainingLength
|
|
||||||
p.TopicName = decodeString(b)
|
|
||||||
if p.Qos > 0 {
|
|
||||||
p.MessageID = decodeUint16(b)
|
|
||||||
payloadLength -= len(p.TopicName) + 4
|
|
||||||
} else {
|
|
||||||
payloadLength -= len(p.TopicName) + 2
|
|
||||||
}
|
|
||||||
if payloadLength < 0 {
|
|
||||||
return fmt.Errorf("Error upacking publish, payload length < 0")
|
|
||||||
}
|
|
||||||
p.Payload = make([]byte, payloadLength)
|
|
||||||
_, err := b.Read(p.Payload)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Copy creates a new PublishPacket with the same topic and payload
|
|
||||||
//but an empty fixed header, useful for when you want to deliver
|
|
||||||
//a message with different properties such as Qos but the same
|
|
||||||
//content
|
|
||||||
func (p *PublishPacket) Copy() *PublishPacket {
|
|
||||||
newP := NewControlPacket(Publish).(*PublishPacket)
|
|
||||||
newP.TopicName = p.TopicName
|
|
||||||
newP.Payload = p.Payload
|
|
||||||
|
|
||||||
return newP
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (p *PublishPacket) Details() Details {
|
|
||||||
return Details{Qos: p.Qos, MessageID: p.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PubrecPacket is an internal representation of the fields of the
|
|
||||||
//Pubrec MQTT packet
|
|
||||||
type PubrecPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PubrecPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PubrecPacket) Write(w io.Writer) error {
|
|
||||||
var err error
|
|
||||||
pr.FixedHeader.RemainingLength = 2
|
|
||||||
packet := pr.FixedHeader.pack()
|
|
||||||
packet.Write(encodeUint16(pr.MessageID))
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pr *PubrecPacket) Unpack(b io.Reader) error {
|
|
||||||
pr.MessageID = decodeUint16(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pr *PubrecPacket) Details() Details {
|
|
||||||
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//PubrelPacket is an internal representation of the fields of the
|
|
||||||
//Pubrel MQTT packet
|
|
||||||
type PubrelPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PubrelPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", pr.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", pr.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (pr *PubrelPacket) Write(w io.Writer) error {
|
|
||||||
var err error
|
|
||||||
pr.FixedHeader.RemainingLength = 2
|
|
||||||
packet := pr.FixedHeader.pack()
|
|
||||||
packet.Write(encodeUint16(pr.MessageID))
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (pr *PubrelPacket) Unpack(b io.Reader) error {
|
|
||||||
pr.MessageID = decodeUint16(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (pr *PubrelPacket) Details() Details {
|
|
||||||
return Details{Qos: pr.Qos, MessageID: pr.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//SubackPacket is an internal representation of the fields of the
|
|
||||||
//Suback MQTT packet
|
|
||||||
type SubackPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
ReturnCodes []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sa *SubackPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", sa.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", sa.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (sa *SubackPacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
body.Write(encodeUint16(sa.MessageID))
|
|
||||||
body.Write(sa.ReturnCodes)
|
|
||||||
sa.FixedHeader.RemainingLength = body.Len()
|
|
||||||
packet := sa.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (sa *SubackPacket) Unpack(b io.Reader) error {
|
|
||||||
var qosBuffer bytes.Buffer
|
|
||||||
sa.MessageID = decodeUint16(b)
|
|
||||||
qosBuffer.ReadFrom(b)
|
|
||||||
sa.ReturnCodes = qosBuffer.Bytes()
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (sa *SubackPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: sa.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,62 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//SubscribePacket is an internal representation of the fields of the
|
|
||||||
//Subscribe MQTT packet
|
|
||||||
type SubscribePacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
Topics []string
|
|
||||||
Qoss []byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SubscribePacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", s.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d topics: %s", s.MessageID, s.Topics)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *SubscribePacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
|
|
||||||
body.Write(encodeUint16(s.MessageID))
|
|
||||||
for i, topic := range s.Topics {
|
|
||||||
body.Write(encodeString(topic))
|
|
||||||
body.WriteByte(s.Qoss[i])
|
|
||||||
}
|
|
||||||
s.FixedHeader.RemainingLength = body.Len()
|
|
||||||
packet := s.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (s *SubscribePacket) Unpack(b io.Reader) error {
|
|
||||||
s.MessageID = decodeUint16(b)
|
|
||||||
payloadLength := s.FixedHeader.RemainingLength - 2
|
|
||||||
for payloadLength > 0 {
|
|
||||||
topic := decodeString(b)
|
|
||||||
s.Topics = append(s.Topics, topic)
|
|
||||||
qos := decodeByte(b)
|
|
||||||
s.Qoss = append(s.Qoss, qos)
|
|
||||||
payloadLength -= 2 + len(topic) + 1 //2 bytes of string length, plus string, plus 1 byte for Qos
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (s *SubscribePacket) Details() Details {
|
|
||||||
return Details{Qos: 1, MessageID: s.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//UnsubackPacket is an internal representation of the fields of the
|
|
||||||
//Unsuback MQTT packet
|
|
||||||
type UnsubackPacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ua *UnsubackPacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", ua.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", ua.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ua *UnsubackPacket) Write(w io.Writer) error {
|
|
||||||
var err error
|
|
||||||
ua.FixedHeader.RemainingLength = 2
|
|
||||||
packet := ua.FixedHeader.pack()
|
|
||||||
packet.Write(encodeUint16(ua.MessageID))
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (ua *UnsubackPacket) Unpack(b io.Reader) error {
|
|
||||||
ua.MessageID = decodeUint16(b)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (ua *UnsubackPacket) Details() Details {
|
|
||||||
return Details{Qos: 0, MessageID: ua.MessageID}
|
|
||||||
}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
package packets
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
)
|
|
||||||
|
|
||||||
//UnsubscribePacket is an internal representation of the fields of the
|
|
||||||
//Unsubscribe MQTT packet
|
|
||||||
type UnsubscribePacket struct {
|
|
||||||
FixedHeader
|
|
||||||
MessageID uint16
|
|
||||||
Topics []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *UnsubscribePacket) String() string {
|
|
||||||
str := fmt.Sprintf("%s", u.FixedHeader)
|
|
||||||
str += " "
|
|
||||||
str += fmt.Sprintf("MessageID: %d", u.MessageID)
|
|
||||||
return str
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *UnsubscribePacket) Write(w io.Writer) error {
|
|
||||||
var body bytes.Buffer
|
|
||||||
var err error
|
|
||||||
body.Write(encodeUint16(u.MessageID))
|
|
||||||
for _, topic := range u.Topics {
|
|
||||||
body.Write(encodeString(topic))
|
|
||||||
}
|
|
||||||
u.FixedHeader.RemainingLength = body.Len()
|
|
||||||
packet := u.FixedHeader.pack()
|
|
||||||
packet.Write(body.Bytes())
|
|
||||||
_, err = packet.WriteTo(w)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
//Unpack decodes the details of a ControlPacket after the fixed
|
|
||||||
//header has been read
|
|
||||||
func (u *UnsubscribePacket) Unpack(b io.Reader) error {
|
|
||||||
u.MessageID = decodeUint16(b)
|
|
||||||
var topic string
|
|
||||||
for topic = decodeString(b); topic != ""; topic = decodeString(b) {
|
|
||||||
u.Topics = append(u.Topics, topic)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
//Details returns a Details struct containing the Qos and
|
|
||||||
//MessageID of this ControlPacket
|
|
||||||
func (u *UnsubscribePacket) Details() Details {
|
|
||||||
return Details{Qos: 1, MessageID: u.MessageID}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user