mirror of
https://github.com/fhmq/hmq.git
synced 2026-05-02 14:28:34 +00:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f92087eada | ||
|
|
a8465585b9 | ||
|
|
8337e14452 | ||
|
|
9dac0e0f1e | ||
|
|
4dc8a703a9 | ||
|
|
83db82cdcc | ||
|
|
b3653bcfb1 | ||
|
|
221d00480e | ||
|
|
91733bf91e | ||
|
|
ef252550dc | ||
|
|
1058256235 | ||
|
|
5a569f14a3 | ||
|
|
93b21777ff | ||
|
|
dcf2934e1b | ||
|
|
d9e6e216b0 | ||
|
|
ca3951769a | ||
|
|
0439e7ce90 | ||
|
|
dc0f2185ab | ||
|
|
7462afcfb5 | ||
|
|
114e6f901e | ||
|
|
0cb51bd37a | ||
|
|
819b4725f2 | ||
|
|
85bdeccbfc |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
hmq
|
hmq
|
||||||
log
|
log
|
||||||
log/*
|
log/*
|
||||||
|
*.test
|
||||||
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.
|
||||||
50
README.md
50
README.md
@@ -3,16 +3,42 @@ 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: hmq [options]
|
||||||
|
|
||||||
|
Broker Options:
|
||||||
|
-w, --worker <number> Worker num to process message, perfer (client num)/10. (default 1024)
|
||||||
|
-p, --port <port> Use port for clients (default: 1883)
|
||||||
|
--host <host> Network host to listen on. (default "0.0.0.0")
|
||||||
|
-ws, --wsport <port> Use port for websocket monitoring
|
||||||
|
-wsp,--wspath <path> Use path for websocket monitoring
|
||||||
|
-c, --config <file> Configuration file
|
||||||
|
|
||||||
|
Logging Options:
|
||||||
|
-d, --debug <bool> Enable debugging output (default false)
|
||||||
|
-D Debug and trace
|
||||||
|
|
||||||
|
Cluster Options:
|
||||||
|
-r, --router <rurl> Router who maintenance cluster info
|
||||||
|
-cp, --clusterport <cluster-port> Cluster listen port for others
|
||||||
|
|
||||||
|
Common Options:
|
||||||
|
-h, --help Show this message
|
||||||
|
~~~
|
||||||
|
|
||||||
|
### hmq.config
|
||||||
~~~
|
~~~
|
||||||
{
|
{
|
||||||
"workerNum": 4096,
|
"workerNum": 4096,
|
||||||
@@ -20,9 +46,9 @@ $ go run main.go
|
|||||||
"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,
|
||||||
@@ -59,6 +85,16 @@ $ go run main.go
|
|||||||
|
|
||||||
* Flexible ACL
|
* Flexible ACL
|
||||||
|
|
||||||
|
### Cluster
|
||||||
|
```bash
|
||||||
|
1, start router for hmq (https://github.com/fhmq/router.git)
|
||||||
|
$ go get github.com/fhmq/router
|
||||||
|
$ cd $GOPATH/github.com/fhmq/router
|
||||||
|
$ go run main.go
|
||||||
|
2, config router in hmq.config ("router": "127.0.0.1:9888")
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
### QUEUE SUBSCRIBE
|
### QUEUE SUBSCRIBE
|
||||||
~~~
|
~~~
|
||||||
| Prefix | Examples |
|
| Prefix | Examples |
|
||||||
@@ -129,4 +165,4 @@ Client -> | Rule1 | --nomatch--> | Rule2 | --nomatch--> | Rule3 | -->
|
|||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
* Apache License Version 2.0
|
* Apache License Version 2.0
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
|
/* 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 +44,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)
|
brokerLog.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)
|
brokerLog.Error("aclconfig change failed, load acl conf error: ", zap.Error(err))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
b.AclConfig = aclconfig
|
b.AclConfig = aclconfig
|
||||||
@@ -56,24 +60,24 @@ 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)
|
brokerLog.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)
|
brokerLog.Error("start monitor acl config file error,", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Info("watching acl config file change...")
|
brokerLog.Info("watching acl config file change...")
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
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())
|
brokerLog.Error("error:", zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
289
broker/broker.go
289
broker/broker.go
@@ -1,8 +1,9 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"hmq/lib/acl"
|
|
||||||
"net"
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
@@ -10,41 +11,60 @@ import (
|
|||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/fhmq/hmq/lib/acl"
|
||||||
|
"github.com/fhmq/hmq/pool"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
"github.com/shirou/gopsutil/mem"
|
"github.com/shirou/gopsutil/mem"
|
||||||
|
"go.uber.org/zap"
|
||||||
|
|
||||||
"golang.org/x/net/websocket"
|
"golang.org/x/net/websocket"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
brokerLog *zap.Logger
|
||||||
|
)
|
||||||
|
|
||||||
|
type Message struct {
|
||||||
|
client *client
|
||||||
|
packet packets.ControlPacket
|
||||||
|
}
|
||||||
|
|
||||||
type Broker struct {
|
type Broker struct {
|
||||||
id string
|
id string
|
||||||
cid uint64
|
cid uint64
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
config *Config
|
config *Config
|
||||||
tlsConfig *tls.Config
|
tlsConfig *tls.Config
|
||||||
AclConfig *acl.ACLConfig
|
AclConfig *acl.ACLConfig
|
||||||
clients sync.Map
|
wpool *pool.WorkerPool
|
||||||
routes sync.Map
|
clients sync.Map
|
||||||
remotes sync.Map
|
routes sync.Map
|
||||||
sl *Sublist
|
remotes sync.Map
|
||||||
rl *RetainList
|
nodes map[string]interface{}
|
||||||
queues map[string]int
|
clusterPool chan *Message
|
||||||
|
messagePool chan *Message
|
||||||
|
sl *Sublist
|
||||||
|
rl *RetainList
|
||||||
|
queues map[string]int
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewBroker(config *Config) (*Broker, error) {
|
func NewBroker(config *Config) (*Broker, error) {
|
||||||
b := &Broker{
|
b := &Broker{
|
||||||
id: GenUniqueId(),
|
id: GenUniqueId(),
|
||||||
config: config,
|
config: config,
|
||||||
sl: NewSublist(),
|
wpool: pool.New(config.Worker),
|
||||||
rl: NewRetainList(),
|
sl: NewSublist(),
|
||||||
queues: make(map[string]int),
|
rl: NewRetainList(),
|
||||||
|
nodes: make(map[string]interface{}),
|
||||||
|
queues: make(map[string]int),
|
||||||
|
clusterPool: make(chan *Message),
|
||||||
|
messagePool: make(chan *Message),
|
||||||
}
|
}
|
||||||
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)
|
brokerLog.Error("new tlsConfig error", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
b.tlsConfig = tlsconfig
|
b.tlsConfig = tlsconfig
|
||||||
@@ -52,7 +72,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)
|
brokerLog.Error("Load acl conf error", zap.Error(err))
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
b.AclConfig = aclconfig
|
b.AclConfig = aclconfig
|
||||||
@@ -61,12 +81,26 @@ func NewBroker(config *Config) (*Broker, error) {
|
|||||||
return b, nil
|
return b, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (b *Broker) StartDispatcher() {
|
||||||
|
for {
|
||||||
|
msg, ok := <-b.messagePool
|
||||||
|
if !ok {
|
||||||
|
brokerLog.Error("read message from client channel error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.wpool.Submit(func() {
|
||||||
|
ProcessMessage(msg)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
func (b *Broker) Start() {
|
func (b *Broker) Start() {
|
||||||
if b == nil {
|
if b == nil {
|
||||||
log.Error("broker is null")
|
brokerLog.Error("broker is null")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
StartDispatcher()
|
go b.StartDispatcher()
|
||||||
|
|
||||||
//listen clinet over tcp
|
//listen clinet over tcp
|
||||||
if b.config.Port != "" {
|
if b.config.Port != "" {
|
||||||
@@ -89,11 +123,12 @@ func (b *Broker) Start() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//connect on other node in cluster
|
//connect on other node in cluster
|
||||||
if len(b.config.Cluster.Routes) > 0 {
|
if b.config.Router != "" {
|
||||||
b.ConnectToRouters()
|
go b.processClusterInfo()
|
||||||
|
b.ConnectToDiscovery()
|
||||||
}
|
}
|
||||||
|
|
||||||
//system montior
|
//system monitor
|
||||||
go StateMonitor()
|
go StateMonitor()
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -114,7 +149,7 @@ func StateMonitor() {
|
|||||||
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)
|
brokerLog.Info("Start Websocket Listener on:", zap.String("hp", hp), zap.String("path", path))
|
||||||
http.Handle(path, websocket.Handler(b.wsHandler))
|
http.Handle(path, websocket.Handler(b.wsHandler))
|
||||||
var err error
|
var err error
|
||||||
if b.config.WsTLS {
|
if b.config.WsTLS {
|
||||||
@@ -123,7 +158,7 @@ func (b *Broker) StartWebsocketListening() {
|
|||||||
err = http.ListenAndServe(hp, nil)
|
err = http.ListenAndServe(hp, nil)
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("ListenAndServe: " + err.Error())
|
brokerLog.Error("ListenAndServe:" + err.Error())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,14 +177,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)
|
brokerLog.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)
|
brokerLog.Info("Start Listening client on ", zap.String("hp", hp))
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Error listening on ", err)
|
brokerLog.Error("Error listening on ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
tmpDelay := 10 * ACCEPT_MIN_SLEEP
|
tmpDelay := 10 * ACCEPT_MIN_SLEEP
|
||||||
@@ -157,15 +192,15 @@ func (b *Broker) StartClientListening(Tls bool) {
|
|||||||
conn, err := l.Accept()
|
conn, err := l.Accept()
|
||||||
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",
|
brokerLog.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)
|
brokerLog.Error("Accept error: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -184,7 +219,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)
|
brokerLog.Error("TLS handshake error, ", zap.Error(err))
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
nc.SetReadDeadline(time.Time{})
|
nc.SetReadDeadline(time.Time{})
|
||||||
@@ -200,18 +235,18 @@ func TlsTimeout(conn *tls.Conn) {
|
|||||||
}
|
}
|
||||||
cs := nc.ConnectionState()
|
cs := nc.ConnectionState()
|
||||||
if !cs.HandshakeComplete {
|
if !cs.HandshakeComplete {
|
||||||
log.Error("TLS handshake timeout")
|
brokerLog.Error("TLS handshake timeout")
|
||||||
nc.Close()
|
nc.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
brokerLog.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)
|
brokerLog.Error("Error listening on ", zap.Error(e))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,15 +256,15 @@ func (b *Broker) StartClusterListening() {
|
|||||||
conn, err := l.Accept()
|
conn, err := l.Accept()
|
||||||
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",
|
brokerLog.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)
|
brokerLog.Error("Accept error: %v", zap.Error(err))
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -243,16 +278,16 @@ 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)
|
brokerLog.Error("read connect packet error: ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if packet == nil {
|
if packet == nil {
|
||||||
log.Error("received nil packet")
|
brokerLog.Error("received nil packet")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
msg, ok := packet.(*packets.ConnectPacket)
|
msg, ok := packet.(*packets.ConnectPacket)
|
||||||
if !ok {
|
if !ok {
|
||||||
log.Error("received msg that was not Connect")
|
brokerLog.Error("received msg that was not Connect")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
connack := packets.NewControlPacket(packets.Connack).(*packets.ConnackPacket)
|
connack := packets.NewControlPacket(packets.Connack).(*packets.ConnackPacket)
|
||||||
@@ -260,7 +295,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, " clientID = ", msg.ClientIdentifier)
|
brokerLog.Error("send connack error, ", zap.Error(err), zap.String("clientID", msg.ClientIdentifier))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,68 +328,135 @@ func (b *Broker) handleConnection(typ int, conn net.Conn, idx uint64) {
|
|||||||
|
|
||||||
cid := c.info.clientID
|
cid := c.info.clientID
|
||||||
|
|
||||||
var msgPool *MessagePool
|
|
||||||
var exist bool
|
var exist bool
|
||||||
var old interface{}
|
var old interface{}
|
||||||
|
|
||||||
switch typ {
|
switch typ {
|
||||||
case CLIENT:
|
case CLIENT:
|
||||||
msgPool = MSGPool[idx%MessagePoolNum].GetPool()
|
|
||||||
c.mp = msgPool
|
|
||||||
old, exist = b.clients.Load(cid)
|
old, exist = b.clients.Load(cid)
|
||||||
if exist {
|
if exist {
|
||||||
log.Warn("client exist, close old...", " clientID = ", c.info.clientID)
|
brokerLog.Warn("client exist, close old...", zap.String("clientID", c.info.clientID))
|
||||||
ol, ok := old.(*client)
|
ol, ok := old.(*client)
|
||||||
if ok {
|
if ok {
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
ol.Close()
|
||||||
ol.mp.queue <- msg
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b.clients.Store(cid, c)
|
b.clients.Store(cid, c)
|
||||||
case ROUTER:
|
case ROUTER:
|
||||||
msgPool = MSGPool[(MessagePoolNum + idx)].GetPool()
|
|
||||||
c.mp = msgPool
|
|
||||||
old, exist = b.routes.Load(cid)
|
old, exist = b.routes.Load(cid)
|
||||||
if exist {
|
if exist {
|
||||||
log.Warn("router exist, close old...")
|
brokerLog.Warn("router exist, close old...")
|
||||||
ol, ok := old.(*client)
|
ol, ok := old.(*client)
|
||||||
if ok {
|
if ok {
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
ol.Close()
|
||||||
ol.mp.queue <- msg
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
b.routes.Store(cid, c)
|
b.routes.Store(cid, c)
|
||||||
}
|
}
|
||||||
|
|
||||||
go c.readLoop()
|
c.readLoop(b.messagePool)
|
||||||
if typ == ROUTER {
|
|
||||||
c.SendInfo()
|
|
||||||
c.StartPing()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) ConnectToRouters() {
|
func (b *Broker) ConnectToDiscovery() {
|
||||||
for _, v := range b.config.Cluster.Routes {
|
|
||||||
go b.connectRouter(v, "")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (b *Broker) connectRouter(url, remoteID string) {
|
|
||||||
var conn net.Conn
|
var conn net.Conn
|
||||||
var err error
|
var err error
|
||||||
|
var tempDelay time.Duration = 0
|
||||||
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)
|
brokerLog.Error("Error trying to connect to route: ", zap.Error(err))
|
||||||
log.Debug("Connect to route timeout ,retry...")
|
brokerLog.Debug("Connect to route timeout ,retry...")
|
||||||
time.Sleep(5 * time.Second)
|
|
||||||
|
if 0 == tempDelay {
|
||||||
|
tempDelay = 1 * time.Second
|
||||||
|
} else {
|
||||||
|
tempDelay *= 2
|
||||||
|
}
|
||||||
|
|
||||||
|
if max := 20 * time.Second; tempDelay > max {
|
||||||
|
tempDelay = max
|
||||||
|
}
|
||||||
|
time.Sleep(tempDelay)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
brokerLog.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()
|
||||||
|
|
||||||
|
go c.readLoop(b.clusterPool)
|
||||||
|
go c.StartPing()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Broker) processClusterInfo() {
|
||||||
|
for {
|
||||||
|
msg, ok := <-b.clusterPool
|
||||||
|
if !ok {
|
||||||
|
brokerLog.Error("read message from cluster channel error")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ProcessMessage(msg)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
brokerLog.Error("Error trying to connect to route: ", zap.Error(err))
|
||||||
|
|
||||||
|
if retryTimes > 50 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
brokerLog.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
|
continue
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
route := route{
|
route := route{
|
||||||
remoteID: remoteID,
|
remoteID: id,
|
||||||
remoteUrl: conn.RemoteAddr().String(),
|
remoteUrl: addr,
|
||||||
}
|
}
|
||||||
cid := GenUniqueId()
|
cid := GenUniqueId()
|
||||||
|
|
||||||
@@ -373,16 +475,35 @@ func (b *Broker) connectRouter(url, remoteID string) {
|
|||||||
c.init()
|
c.init()
|
||||||
b.remotes.Store(cid, c)
|
b.remotes.Store(cid, c)
|
||||||
|
|
||||||
c.mp = MSGPool[(MessagePoolNum + 1)].GetPool()
|
|
||||||
|
|
||||||
c.SendConnect()
|
c.SendConnect()
|
||||||
c.SendInfo()
|
|
||||||
|
|
||||||
go c.readLoop()
|
go c.readLoop(b.messagePool)
|
||||||
go c.StartPing()
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (b *Broker) CheckRemoteExist(remoteID, url string) bool {
|
func (b *Broker) CheckRemoteExist(remoteID, url string) bool {
|
||||||
exist := false
|
exist := false
|
||||||
b.remotes.Range(func(key, value interface{}) bool {
|
b.remotes.Range(func(key, value interface{}) bool {
|
||||||
@@ -415,7 +536,7 @@ func (b *Broker) SendLocalSubsToRouter(c *client) {
|
|||||||
if len(subInfo.Topics) > 0 {
|
if len(subInfo.Topics) > 0 {
|
||||||
err := c.WriterPacket(subInfo)
|
err := c.WriterPacket(subInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Send localsubs To Router error :", err)
|
brokerLog.Error("Send localsubs To Router error :", zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -432,7 +553,7 @@ func (b *Broker) BroadcastInfoMessage(remoteID string, msg *packets.PublishPacke
|
|||||||
return true
|
return true
|
||||||
|
|
||||||
})
|
})
|
||||||
// log.Info("BroadcastInfoMessage success ")
|
// brokerLog.Info("BroadcastInfoMessage success ")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) BroadcastSubOrUnsubMessage(packet packets.ControlPacket) {
|
func (b *Broker) BroadcastSubOrUnsubMessage(packet packets.ControlPacket) {
|
||||||
@@ -444,7 +565,7 @@ func (b *Broker) BroadcastSubOrUnsubMessage(packet packets.ControlPacket) {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
})
|
})
|
||||||
// log.Info("BroadcastSubscribeMessage remotes: ", s.remotes)
|
// brokerLog.Info("BroadcastSubscribeMessage remotes: ", s.remotes)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) removeClient(c *client) {
|
func (b *Broker) removeClient(c *client) {
|
||||||
@@ -458,7 +579,7 @@ func (b *Broker) removeClient(c *client) {
|
|||||||
case REMOTE:
|
case REMOTE:
|
||||||
b.remotes.Delete(clientId)
|
b.remotes.Delete(clientId)
|
||||||
}
|
}
|
||||||
// log.Info("delete client ,", clientId)
|
// brokerLog.Info("delete client ,", clientId)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
func (b *Broker) PublishMessage(packet *packets.PublishPacket) {
|
||||||
@@ -472,7 +593,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)
|
brokerLog.Error("process message for psub error, ", zap.Error(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,28 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"github.com/eclipse/paho.mqtt.golang/packets"
|
||||||
|
"go.uber.org/zap"
|
||||||
log "github.com/cihub/seelog"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
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 (
|
const (
|
||||||
Connected = 1
|
Connected = 1
|
||||||
@@ -36,7 +39,6 @@ type client struct {
|
|||||||
status int
|
status int
|
||||||
closed chan int
|
closed chan int
|
||||||
smu sync.RWMutex
|
smu sync.RWMutex
|
||||||
mp *MessagePool
|
|
||||||
subs map[string]*subscription
|
subs map[string]*subscription
|
||||||
rsubs map[string]*subInfo
|
rsubs map[string]*subInfo
|
||||||
}
|
}
|
||||||
@@ -84,20 +86,23 @@ func (c *client) init() {
|
|||||||
c.info.remoteIP = strings.Split(c.conn.RemoteAddr().String(), ":")[0]
|
c.info.remoteIP = strings.Split(c.conn.RemoteAddr().String(), ":")[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) keepAlive(ch chan int) {
|
func (c *client) keepAlive(ch chan int, mpool chan *Message) {
|
||||||
defer close(ch)
|
defer close(ch)
|
||||||
keepalive := time.Duration(c.info.keepalive*3/2) * time.Second
|
keepalive := time.Duration(c.info.keepalive*3/2) * time.Second
|
||||||
timer := time.NewTimer(keepalive)
|
timer := time.NewTimer(keepalive)
|
||||||
msgPool := c.mp
|
|
||||||
|
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ch:
|
case <-ch:
|
||||||
timer.Reset(keepalive)
|
timer.Reset(keepalive)
|
||||||
case <-timer.C:
|
case <-timer.C:
|
||||||
log.Error("Client exceeded timeout, disconnecting. clientID = ", c.info.clientID, " keepalive = ", c.info.keepalive)
|
if c.typ == REMOTE || c.typ == CLUSTER {
|
||||||
|
timer.Reset(keepalive)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
brokerLog.Error("Client exceeded timeout, disconnecting. ", zap.String("ClientID", c.info.clientID), zap.Uint16("keepalive", c.info.keepalive))
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
msgPool.queue <- msg
|
mpool <- msg
|
||||||
timer.Stop()
|
timer.Stop()
|
||||||
return
|
return
|
||||||
case _, ok := <-c.closed:
|
case _, ok := <-c.closed:
|
||||||
@@ -108,34 +113,33 @@ func (c *client) keepAlive(ch chan int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *client) readLoop() {
|
func (c *client) readLoop(mpool chan *Message) {
|
||||||
nc := c.conn
|
nc := c.conn
|
||||||
msgPool := c.mp
|
if nc == nil || mpool == nil {
|
||||||
if nc == nil || msgPool == nil {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ch := make(chan int, 1000)
|
ch := make(chan int, 1000)
|
||||||
go c.keepAlive(ch)
|
go c.keepAlive(ch, mpool)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
packet, err := packets.ReadPacket(nc)
|
packet, err := packets.ReadPacket(nc)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("read packet error: ", err, " clientID = ", c.info.clientID)
|
brokerLog.Error("read packet error: ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
|
// keepalive channel
|
||||||
ch <- 1
|
ch <- 1
|
||||||
|
|
||||||
msg := &Message{
|
msg := &Message{
|
||||||
client: c,
|
client: c,
|
||||||
packet: packet,
|
packet: packet,
|
||||||
}
|
}
|
||||||
msgPool.queue <- msg
|
mpool <- msg
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := &Message{client: c, packet: DisconnectdPacket}
|
msg := &Message{client: c, packet: DisconnectdPacket}
|
||||||
msgPool.queue <- msg
|
mpool <- msg
|
||||||
msgPool.Reduce()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func ProcessMessage(msg *Message) {
|
func ProcessMessage(msg *Message) {
|
||||||
@@ -144,10 +148,10 @@ func ProcessMessage(msg *Message) {
|
|||||||
if ca == nil {
|
if ca == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Debug("Recv message: ", ca.String(), " clientID = ", c.info.clientID)
|
|
||||||
|
brokerLog.Debug("Recv message:", zap.String("message type", reflect.TypeOf(msg.packet).String()[9:]), zap.String("ClientID", c.info.clientID))
|
||||||
switch ca.(type) {
|
switch ca.(type) {
|
||||||
case *packets.ConnackPacket:
|
case *packets.ConnackPacket:
|
||||||
|
|
||||||
case *packets.ConnectPacket:
|
case *packets.ConnectPacket:
|
||||||
case *packets.PublishPacket:
|
case *packets.PublishPacket:
|
||||||
packet := ca.(*packets.PublishPacket)
|
packet := ca.(*packets.PublishPacket)
|
||||||
@@ -170,7 +174,7 @@ func ProcessMessage(msg *Message) {
|
|||||||
case *packets.DisconnectPacket:
|
case *packets.DisconnectPacket:
|
||||||
c.Close()
|
c.Close()
|
||||||
default:
|
default:
|
||||||
log.Info("Recv Unknow message.......", " clientID = ", c.info.clientID)
|
brokerLog.Info("Recv Unknow message.......", zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,13 +184,13 @@ func (c *client) ProcessPublish(packet *packets.PublishPacket) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
topic := packet.TopicName
|
topic := packet.TopicName
|
||||||
if topic == BrokerInfoTopic && c.typ != CLIENT {
|
if topic == BrokerInfoTopic && c.typ == CLUSTER {
|
||||||
c.ProcessInfo(packet)
|
c.ProcessInfo(packet)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !c.CheckTopicAuth(PUB, topic) {
|
if !c.CheckTopicAuth(PUB, topic) {
|
||||||
log.Error("Pub Topics Auth failed, ", topic, " clientID = ", c.info.clientID)
|
brokerLog.Error("Pub Topics Auth failed, ", zap.String("topic", topic), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,21 +201,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, " clientID = ", c.info.clientID)
|
brokerLog.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", " clientID = ", c.info.clientID)
|
brokerLog.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, " clientID = ", c.info.clientID)
|
brokerLog.Error("Insert Retain Message error: ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -231,21 +235,21 @@ func (c *client) ProcessPublishMessage(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))
|
// brokerLog.Info("psubs num: ", len(r.psubs))
|
||||||
if len(r.qsubs) == 0 && len(r.psubs) == 0 {
|
if len(r.qsubs) == 0 && len(r.psubs) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, sub := range r.psubs {
|
for _, sub := range r.psubs {
|
||||||
if sub.client.typ == REMOTE {
|
if sub.client.typ == ROUTER {
|
||||||
if typ == REMOTE {
|
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, " clientID = ", c.info.clientID)
|
brokerLog.Error("process message for psub error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -255,10 +259,10 @@ func (c *client) ProcessPublishMessage(packet *packets.PublishPacket) {
|
|||||||
t := "$queue/" + topic
|
t := "$queue/" + topic
|
||||||
cnt, exist := b.queues[t]
|
cnt, exist := b.queues[t]
|
||||||
if exist {
|
if exist {
|
||||||
// log.Info("queue index : ", cnt)
|
// brokerLog.Info("queue index : ", cnt)
|
||||||
for _, sub := range r.qsubs {
|
for _, sub := range r.qsubs {
|
||||||
if sub.client.typ == REMOTE {
|
if sub.client.typ == ROUTER {
|
||||||
if c.typ == REMOTE {
|
if typ != CLIENT {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,7 +275,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, " clientID = ", c.info.clientID)
|
brokerLog.Error("send publish error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +329,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, " clientID = ", c.info.clientID)
|
brokerLog.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
|
||||||
}
|
}
|
||||||
@@ -359,7 +363,7 @@ func (c *client) ProcessSubscribe(packet *packets.SubscribePacket) {
|
|||||||
retcodes = append(retcodes, qoss[i])
|
retcodes = append(retcodes, qoss[i])
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
case REMOTE:
|
case ROUTER:
|
||||||
if subinfo, exist := c.rsubs[topic]; !exist {
|
if subinfo, exist := c.rsubs[topic]; !exist {
|
||||||
sinfo := &subInfo{sub: sub, num: 1}
|
sinfo := &subInfo{sub: sub, num: 1}
|
||||||
c.rsubs[topic] = sinfo
|
c.rsubs[topic] = sinfo
|
||||||
@@ -372,7 +376,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, " clientID = ", c.info.clientID)
|
brokerLog.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])
|
||||||
@@ -382,7 +386,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, " clientID = ", c.info.clientID)
|
brokerLog.Error("send suback error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
//broadcast subscribe message
|
//broadcast subscribe message
|
||||||
@@ -394,7 +398,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, " clientID = ", c.info.clientID)
|
brokerLog.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)
|
||||||
}
|
}
|
||||||
@@ -421,7 +425,7 @@ func (c *client) ProcessUnSubscribe(packet *packets.UnsubscribePacket) {
|
|||||||
if ok {
|
if ok {
|
||||||
c.unsubscribe(sub)
|
c.unsubscribe(sub)
|
||||||
}
|
}
|
||||||
case REMOTE:
|
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
|
||||||
@@ -441,7 +445,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, " clientID = ", c.info.clientID)
|
brokerLog.Error("send unsuback error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// //process ubsubscribe message
|
// //process ubsubscribe message
|
||||||
@@ -470,7 +474,7 @@ func (c *client) ProcessPing() {
|
|||||||
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, " clientID = ", c.info.clientID)
|
brokerLog.Error("send PingResponse error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -501,7 +505,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, " clientID = ", c.info.clientID)
|
brokerLog.Error("closed client but remove sublist error, ", zap.Error(err), zap.String("ClientID", c.info.clientID))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.typ == CLIENT {
|
if c.typ == CLIENT {
|
||||||
@@ -511,12 +515,13 @@ func (c *client) Close() {
|
|||||||
b.PublishMessage(c.info.willMsg)
|
b.PublishMessage(c.info.willMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if c.typ == CLUSTER {
|
||||||
|
b.ConnectToDiscovery()
|
||||||
|
}
|
||||||
|
|
||||||
//do reconnect
|
//do reconnect
|
||||||
if c.typ == REMOTE {
|
if c.typ == REMOTE {
|
||||||
localUrl := c.info.localIP + ":" + c.broker.config.Cluster.Port
|
go b.connectRouter(c.route.remoteID, c.route.remoteUrl)
|
||||||
if c.route.remoteUrl != localUrl {
|
|
||||||
b.connectRouter(c.route.remoteUrl, "")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
|||||||
133
broker/config.go
133
broker/config.go
@@ -1,17 +1,19 @@
|
|||||||
|
/* 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"
|
||||||
|
"os"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/fhmq/hmq/logger"
|
||||||
)
|
"go.uber.org/zap"
|
||||||
|
|
||||||
const (
|
|
||||||
CONFIGFILE = "conf/hmq.config"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
@@ -19,6 +21,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"`
|
||||||
@@ -27,12 +30,12 @@ type Config struct {
|
|||||||
TlsInfo TLSInfo `json:"tlsInfo"`
|
TlsInfo TLSInfo `json:"tlsInfo"`
|
||||||
Acl bool `json:"acl"`
|
Acl bool `json:"acl"`
|
||||||
AclConf string `json:"aclConf"`
|
AclConf string `json:"aclConf"`
|
||||||
|
Debug bool `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
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,28 +45,110 @@ 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 showHelp() {
|
||||||
if err != nil {
|
fmt.Printf("%s\n", usageStr)
|
||||||
log.Error("Read config file error: ", err)
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConfigureConfig(args []string) (*Config, error) {
|
||||||
|
config := &Config{}
|
||||||
|
var (
|
||||||
|
help bool
|
||||||
|
configFile string
|
||||||
|
)
|
||||||
|
fs := flag.NewFlagSet("hmq-broker", flag.ExitOnError)
|
||||||
|
fs.Usage = showHelp
|
||||||
|
|
||||||
|
fs.BoolVar(&help, "h", false, "Show this message.")
|
||||||
|
fs.BoolVar(&help, "help", false, "Show this message.")
|
||||||
|
fs.IntVar(&config.Worker, "w", 1024, "worker num to process message, perfer (client num)/10.")
|
||||||
|
fs.IntVar(&config.Worker, "worker", 1024, "worker num to process message, perfer (client num)/10.")
|
||||||
|
fs.StringVar(&config.Port, "port", "1883", "Port to listen on.")
|
||||||
|
fs.StringVar(&config.Port, "p", "1883", "Port to listen on.")
|
||||||
|
fs.StringVar(&config.Host, "host", "0.0.0.0", "Network host to listen on")
|
||||||
|
fs.StringVar(&config.Cluster.Port, "cp", "", "Cluster port from which members can connect.")
|
||||||
|
fs.StringVar(&config.Cluster.Port, "clusterport", "", "Cluster port from which members can connect.")
|
||||||
|
fs.StringVar(&config.Router, "r", "", "Router who maintenance cluster info")
|
||||||
|
fs.StringVar(&config.Router, "router", "", "Router who maintenance cluster info")
|
||||||
|
fs.StringVar(&config.WsPort, "ws", "", "port for ws to listen on")
|
||||||
|
fs.StringVar(&config.WsPort, "wsport", "", "port for ws to listen on")
|
||||||
|
fs.StringVar(&config.WsPath, "wsp", "", "path for ws to listen on")
|
||||||
|
fs.StringVar(&config.WsPath, "wspath", "", "path for ws to listen on")
|
||||||
|
fs.StringVar(&configFile, "config", "", "config file for hmq")
|
||||||
|
fs.StringVar(&configFile, "c", "", "config file for hmq")
|
||||||
|
fs.BoolVar(&config.Debug, "debug", false, "enable Debug logging.")
|
||||||
|
fs.BoolVar(&config.Debug, "d", false, "enable Debug logging.")
|
||||||
|
|
||||||
|
fs.Bool("D", true, "enable Debug logging.")
|
||||||
|
|
||||||
|
if err := fs.Parse(args); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
// log.Info(string(content))
|
|
||||||
|
if help {
|
||||||
|
showHelp()
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.Visit(func(f *flag.Flag) {
|
||||||
|
switch f.Name {
|
||||||
|
case "D":
|
||||||
|
config.Debug = true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
logger.InitLogger(config.Debug)
|
||||||
|
brokerLog = logger.Get().Named("Broker")
|
||||||
|
|
||||||
|
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 {
|
||||||
|
brokerLog.Error("Read config file error: ", zap.Error(err))
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// brokerLog.Info(string(content))
|
||||||
|
|
||||||
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)
|
brokerLog.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
|
||||||
}
|
}
|
||||||
|
|
||||||
WorkNum = config.Worker
|
|
||||||
|
|
||||||
if config.Port != "" {
|
if config.Port != "" {
|
||||||
if config.Host == "" {
|
if config.Host == "" {
|
||||||
config.Host = "0.0.0.0"
|
config.Host = "0.0.0.0"
|
||||||
@@ -75,29 +160,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.")
|
brokerLog.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,44 +0,0 @@
|
|||||||
package broker
|
|
||||||
|
|
||||||
var WorkNum int
|
|
||||||
|
|
||||||
type Dispatcher struct {
|
|
||||||
WorkerPool chan chan *Message
|
|
||||||
}
|
|
||||||
|
|
||||||
func StartDispatcher() {
|
|
||||||
InitMessagePool()
|
|
||||||
dispatcher := NewDispatcher()
|
|
||||||
dispatcher.Run()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Dispatcher) Run() {
|
|
||||||
// starting n number of workers
|
|
||||||
for i := 0; i < WorkNum; i++ {
|
|
||||||
worker := NewWorker(d.WorkerPool)
|
|
||||||
worker.Start()
|
|
||||||
}
|
|
||||||
go d.dispatch()
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewDispatcher() *Dispatcher {
|
|
||||||
pool := make(chan chan *Message, WorkNum)
|
|
||||||
return &Dispatcher{WorkerPool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *Dispatcher) dispatch() {
|
|
||||||
for i := 0; i < (MessagePoolNum + 2); i++ {
|
|
||||||
go func(idx int) {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case msg := <-MSGPool[idx].queue:
|
|
||||||
go func(msg *Message) {
|
|
||||||
msgChannel := <-d.WorkerPool
|
|
||||||
msgChannel <- msg
|
|
||||||
}(msg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}(i)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Copyright (c) 2018, joy.zhou <chowyu08@gmail.com>
|
||||||
|
*/
|
||||||
package broker
|
package broker
|
||||||
|
|
||||||
import (
|
import (
|
||||||
@@ -5,9 +7,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
"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() {
|
||||||
@@ -19,20 +21,20 @@ func (c *client) SendInfo() {
|
|||||||
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)
|
brokerLog.Error("send info message error, ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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)
|
brokerLog.Error("ping error: ", zap.Error(err))
|
||||||
c.Close()
|
c.Close()
|
||||||
}
|
}
|
||||||
case _, ok := <-c.closed:
|
case _, ok := <-c.closed:
|
||||||
@@ -55,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)
|
brokerLog.Error("send connect message error, ", zap.Error(err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
log.Info("send connect success")
|
brokerLog.Info("send connect success")
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewInfo(sid, url string, isforword bool) *packets.PublishPacket {
|
func NewInfo(sid, url string, isforword bool) *packets.PublishPacket {
|
||||||
@@ -66,8 +68,8 @@ 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))
|
// brokerLog.Info("new info", string(info))
|
||||||
pub.Payload = []byte(info)
|
pub.Payload = []byte(info)
|
||||||
return pub
|
return pub
|
||||||
}
|
}
|
||||||
@@ -79,51 +81,36 @@ func (c *client) ProcessInfo(packet *packets.PublishPacket) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Info("recv remoteInfo: ", string(packet.Payload))
|
brokerLog.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)
|
brokerLog.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()
|
brokerLog.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
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
b.mu.Lock()
|
b.mu.Lock()
|
||||||
exist := b.CheckRemoteExist(rid, rurl)
|
for rid, rurl := range routes {
|
||||||
if !exist {
|
if rid == b.id {
|
||||||
b.connectRouter(rurl, rid)
|
continue
|
||||||
}
|
|
||||||
b.mu.Unlock()
|
|
||||||
|
|
||||||
if !isForward {
|
|
||||||
if c.typ == ROUTER {
|
|
||||||
route := route{
|
|
||||||
remoteUrl: rurl,
|
|
||||||
remoteID: rid,
|
|
||||||
}
|
|
||||||
c.route = route
|
|
||||||
}
|
}
|
||||||
|
|
||||||
go b.SendLocalSubsToRouter(c)
|
url, ok := rurl.(string)
|
||||||
// log.Info("BroadcastInfoMessage starting... ")
|
if ok {
|
||||||
infoMsg := NewInfo(rid, rurl, true)
|
exist := b.CheckRemoteExist(rid, url)
|
||||||
b.BroadcastInfoMessage(rid, infoMsg)
|
if !exist {
|
||||||
}
|
b.connectRouter(rid, url)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return
|
}
|
||||||
|
b.mu.Unlock()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,62 +0,0 @@
|
|||||||
package broker
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/eclipse/paho.mqtt.golang/packets"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
MaxUser = 1024 * 1024
|
|
||||||
MessagePoolNum = 1024
|
|
||||||
MessagePoolUser = MaxUser / MessagePoolNum
|
|
||||||
MessagePoolMessageNum = MaxUser / MessagePoolNum * 4
|
|
||||||
)
|
|
||||||
|
|
||||||
type Message struct {
|
|
||||||
client *client
|
|
||||||
packet packets.ControlPacket
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
MSGPool []MessagePool
|
|
||||||
)
|
|
||||||
|
|
||||||
type MessagePool struct {
|
|
||||||
l sync.Mutex
|
|
||||||
maxuser int
|
|
||||||
user int
|
|
||||||
queue chan *Message
|
|
||||||
}
|
|
||||||
|
|
||||||
func InitMessagePool() {
|
|
||||||
MSGPool = make([]MessagePool, (MessagePoolNum + 2))
|
|
||||||
for i := 0; i < (MessagePoolNum + 2); i++ {
|
|
||||||
MSGPool[i].Init(MessagePoolUser, MessagePoolMessageNum)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *MessagePool) Init(num int, maxusernum int) {
|
|
||||||
p.maxuser = maxusernum
|
|
||||||
p.queue = make(chan *Message, num)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *MessagePool) GetPool() *MessagePool {
|
|
||||||
p.l.Lock()
|
|
||||||
if p.user+1 < p.maxuser {
|
|
||||||
p.user += 1
|
|
||||||
p.l.Unlock()
|
|
||||||
return p
|
|
||||||
} else {
|
|
||||||
p.l.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (p *MessagePool) Reduce() {
|
|
||||||
p.l.Lock()
|
|
||||||
p.user -= 1
|
|
||||||
p.l.Unlock()
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -39,7 +39,7 @@ func (r *RetainList) Insert(topic string, buf *packets.PublishPacket) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// log.Info("insert tokens:", tokens)
|
// brokerLog.Info("insert tokens:", tokens)
|
||||||
r.Lock()
|
r.Lock()
|
||||||
|
|
||||||
l := r.root
|
l := r.root
|
||||||
@@ -72,7 +72,7 @@ func (r *RetainList) Match(topic string) []*packets.PublishPacket {
|
|||||||
l := r.root
|
l := r.root
|
||||||
matchRLevel(l, tokens, results)
|
matchRLevel(l, tokens, results)
|
||||||
r.Unlock()
|
r.Unlock()
|
||||||
// log.Info("results: ", results)
|
// brokerLog.Info("results: ", results)
|
||||||
return results.msg
|
return results.msg
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -82,7 +82,7 @@ func matchRLevel(l *rlevel, toks []string, results *RetainResult) {
|
|||||||
if l == nil {
|
if l == nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// log.Info("l info :", l.nodes)
|
// brokerLog.Info("l info :", l.nodes)
|
||||||
if t == "#" {
|
if t == "#" {
|
||||||
for _, n := range l.nodes {
|
for _, n := range l.nodes {
|
||||||
n.GetAll(results)
|
n.GetAll(results)
|
||||||
@@ -111,7 +111,7 @@ func matchRLevel(l *rlevel, toks []string, results *RetainResult) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *rnode) GetAll(results *RetainResult) {
|
func (r *rnode) GetAll(results *RetainResult) {
|
||||||
// log.Info("node 's message: ", string(r.msg))
|
// brokerLog.Info("node 's message: ", string(r.msg))
|
||||||
if r.msg != nil {
|
if r.msg != nil {
|
||||||
results.msg = append(results.msg, r.msg)
|
results.msg = append(results.msg, r.msg)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
brokerLog.Error("\tserver/sublist.go: ", zap.Error(err))
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
24
broker/usage.go
Normal file
24
broker/usage.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
var usageStr = `
|
||||||
|
Usage: hmq [options]
|
||||||
|
|
||||||
|
Broker Options:
|
||||||
|
-w, --worker <number> Worker num to process message, perfer (client num)/10. (default 1024)
|
||||||
|
-p, --port <port> Use port for clients (default: 1883)
|
||||||
|
--host <host> Network host to listen on. (default "0.0.0.0")
|
||||||
|
-ws, --wsport <port> Use port for websocket monitoring
|
||||||
|
-wsp,--wspath <path> Use path for websocket monitoring
|
||||||
|
-c, --config <file> Configuration file
|
||||||
|
|
||||||
|
Logging Options:
|
||||||
|
-d, --debug <bool> Enable debugging output (default false)
|
||||||
|
-D Debug and trace
|
||||||
|
|
||||||
|
Cluster Options:
|
||||||
|
-r, --router <rurl> Router who maintenance cluster info
|
||||||
|
-cp, --clusterport <cluster-port> Cluster listen port for others
|
||||||
|
|
||||||
|
Common Options:
|
||||||
|
-h, --help Show this message
|
||||||
|
`
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
package broker
|
|
||||||
|
|
||||||
type Worker struct {
|
|
||||||
WorkerPool chan chan *Message
|
|
||||||
MsgChannel chan *Message
|
|
||||||
quit chan bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewWorker(workerPool chan chan *Message) Worker {
|
|
||||||
return Worker{
|
|
||||||
WorkerPool: workerPool,
|
|
||||||
MsgChannel: make(chan *Message),
|
|
||||||
quit: make(chan bool)}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w Worker) Start() {
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
// register the current worker into the worker queue.
|
|
||||||
w.WorkerPool <- w.MsgChannel
|
|
||||||
select {
|
|
||||||
case msg := <-w.MsgChannel:
|
|
||||||
// we have received a work request.
|
|
||||||
ProcessMessage(msg)
|
|
||||||
case <-w.quit:
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Stop signals the worker to stop listening for work requests.
|
|
||||||
func (w Worker) Stop() {
|
|
||||||
go func() {
|
|
||||||
w.quit <- true
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
@@ -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 (
|
||||||
|
|||||||
50
logger/logger.go
Normal file
50
logger/logger.go
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
/* 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
|
||||||
|
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 InitLogger(debug bool) {
|
||||||
|
var err error
|
||||||
|
var log *zap.Logger
|
||||||
|
if debug {
|
||||||
|
log, err = NewDevLogger()
|
||||||
|
} else {
|
||||||
|
log, err = NewProdLogger()
|
||||||
|
}
|
||||||
|
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))
|
||||||
|
}
|
||||||
38
main.go
38
main.go
@@ -1,49 +1,37 @@
|
|||||||
|
/* 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"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
log "github.com/cihub/seelog"
|
"github.com/fhmq/hmq/broker"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
|
||||||
testConfig := `
|
|
||||||
<seelog type="sync">
|
|
||||||
<outputs formatid="main">
|
|
||||||
<console/>
|
|
||||||
</outputs>
|
|
||||||
<formats>
|
|
||||||
<format id="main" format="Time:%Date %Time%tfile:%File%tlevel:%LEVEL%t%Msg%n"/>
|
|
||||||
</formats>
|
|
||||||
</seelog>`
|
|
||||||
|
|
||||||
logger, err := log.LoggerFromConfigAsBytes([]byte(testConfig))
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
log.ReplaceLogger(logger)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||||
config, er := broker.LoadConfig()
|
config, err := broker.ConfigureConfig(os.Args[1:])
|
||||||
if er != nil {
|
if err != nil {
|
||||||
log.Error("Load Config file error: ", er)
|
fmt.Println("configure broker config error: ", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
b, err := broker.NewBroker(config)
|
b, err := broker.NewBroker(config)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("New Broker error: ", er)
|
fmt.Println("New Broker error: ", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
b.Start()
|
b.Start()
|
||||||
|
|
||||||
s := waitForSignal()
|
s := waitForSignal()
|
||||||
log.Infof("signal got: %v ,broker closed.", s)
|
fmt.Println("signal received, broker closed.", s)
|
||||||
}
|
}
|
||||||
|
|
||||||
func waitForSignal() os.Signal {
|
func waitForSignal() os.Signal {
|
||||||
|
|||||||
166
pool/pool.go
Normal file
166
pool/pool.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package pool
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
const (
|
||||||
|
// This value is the size of the queue that workers register their
|
||||||
|
// availability to the dispatcher. There may be hundreds of workers, but
|
||||||
|
// only a small channel is needed to register some of the workers.
|
||||||
|
readyQueueSize = 16
|
||||||
|
|
||||||
|
// If worker pool receives no new work for this period of time, then stop
|
||||||
|
// a worker goroutine.
|
||||||
|
idleTimeoutSec = 5
|
||||||
|
)
|
||||||
|
|
||||||
|
type WorkerPool struct {
|
||||||
|
maxWorkers int
|
||||||
|
timeout time.Duration
|
||||||
|
taskQueue chan func()
|
||||||
|
readyWorkers chan chan func()
|
||||||
|
stoppedChan chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(maxWorkers int) *WorkerPool {
|
||||||
|
// There must be at least one worker.
|
||||||
|
if maxWorkers < 1 {
|
||||||
|
maxWorkers = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// taskQueue is unbuffered since items are always removed immediately.
|
||||||
|
pool := &WorkerPool{
|
||||||
|
taskQueue: make(chan func()),
|
||||||
|
maxWorkers: maxWorkers,
|
||||||
|
readyWorkers: make(chan chan func(), readyQueueSize),
|
||||||
|
timeout: time.Second * idleTimeoutSec,
|
||||||
|
stoppedChan: make(chan struct{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start the task dispatcher.
|
||||||
|
go pool.dispatch()
|
||||||
|
|
||||||
|
return pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *WorkerPool) Stop() {
|
||||||
|
if p.Stopped() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
close(p.taskQueue)
|
||||||
|
<-p.stoppedChan
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *WorkerPool) Stopped() bool {
|
||||||
|
select {
|
||||||
|
case <-p.stoppedChan:
|
||||||
|
return true
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *WorkerPool) Submit(task func()) {
|
||||||
|
if task != nil {
|
||||||
|
p.taskQueue <- task
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *WorkerPool) SubmitWait(task func()) {
|
||||||
|
if task == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
doneChan := make(chan struct{})
|
||||||
|
p.taskQueue <- func() {
|
||||||
|
task()
|
||||||
|
close(doneChan)
|
||||||
|
}
|
||||||
|
<-doneChan
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *WorkerPool) dispatch() {
|
||||||
|
defer close(p.stoppedChan)
|
||||||
|
timeout := time.NewTimer(p.timeout)
|
||||||
|
var workerCount int
|
||||||
|
var task func()
|
||||||
|
var ok bool
|
||||||
|
var workerTaskChan chan func()
|
||||||
|
startReady := make(chan chan func())
|
||||||
|
Loop:
|
||||||
|
for {
|
||||||
|
timeout.Reset(p.timeout)
|
||||||
|
select {
|
||||||
|
case task, ok = <-p.taskQueue:
|
||||||
|
if !ok {
|
||||||
|
break Loop
|
||||||
|
}
|
||||||
|
// Got a task to do.
|
||||||
|
select {
|
||||||
|
case workerTaskChan = <-p.readyWorkers:
|
||||||
|
// A worker is ready, so give task to worker.
|
||||||
|
workerTaskChan <- task
|
||||||
|
default:
|
||||||
|
// No workers ready.
|
||||||
|
// Create a new worker, if not at max.
|
||||||
|
if workerCount < p.maxWorkers {
|
||||||
|
workerCount++
|
||||||
|
go func(t func()) {
|
||||||
|
startWorker(startReady, p.readyWorkers)
|
||||||
|
// Submit the task when the new worker.
|
||||||
|
taskChan := <-startReady
|
||||||
|
taskChan <- t
|
||||||
|
}(task)
|
||||||
|
} else {
|
||||||
|
// Start a goroutine to submit the task when an existing
|
||||||
|
// worker is ready.
|
||||||
|
go func(t func()) {
|
||||||
|
taskChan := <-p.readyWorkers
|
||||||
|
taskChan <- t
|
||||||
|
}(task)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case <-timeout.C:
|
||||||
|
// Timed out waiting for work to arrive. Kill a ready worker.
|
||||||
|
if workerCount > 0 {
|
||||||
|
select {
|
||||||
|
case workerTaskChan = <-p.readyWorkers:
|
||||||
|
// A worker is ready, so kill.
|
||||||
|
close(workerTaskChan)
|
||||||
|
workerCount--
|
||||||
|
default:
|
||||||
|
// No work, but no ready workers. All workers are busy.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop all remaining workers as they become ready.
|
||||||
|
for workerCount > 0 {
|
||||||
|
workerTaskChan = <-p.readyWorkers
|
||||||
|
close(workerTaskChan)
|
||||||
|
workerCount--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startWorker(startReady, readyWorkers chan chan func()) {
|
||||||
|
go func() {
|
||||||
|
taskChan := make(chan func())
|
||||||
|
var task func()
|
||||||
|
var ok bool
|
||||||
|
// Register availability on starReady channel.
|
||||||
|
startReady <- taskChan
|
||||||
|
for {
|
||||||
|
// Read task from dispatcher.
|
||||||
|
task, ok = <-taskChan
|
||||||
|
if !ok {
|
||||||
|
// Dispatcher has told worker to stop.
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute the task.
|
||||||
|
task()
|
||||||
|
|
||||||
|
// Register availability on readyWorkers channel.
|
||||||
|
readyWorkers <- taskChan
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user