micro/server/rpc_server.go

908 lines
19 KiB
Go
Raw Normal View History

2015-01-13 23:31:27 +00:00
package server
import (
2018-03-03 11:53:52 +00:00
"context"
"fmt"
2019-09-27 16:01:16 +02:00
"io"
"net"
2015-12-21 17:18:04 +00:00
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
2016-05-12 23:32:58 +01:00
"time"
2015-11-20 16:17:33 +00:00
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/codec"
raw "github.com/micro/go-micro/codec/bytes"
2016-01-28 17:55:28 +00:00
"github.com/micro/go-micro/metadata"
2019-07-07 12:33:54 +01:00
"github.com/micro/go-micro/registry"
2019-07-10 07:47:17 +01:00
"github.com/micro/go-micro/transport"
2019-05-30 23:52:10 +01:00
"github.com/micro/go-micro/util/addr"
2019-05-31 00:38:05 +01:00
log "github.com/micro/go-micro/util/log"
mnet "github.com/micro/go-micro/util/net"
2019-08-15 20:08:49 +01:00
"github.com/micro/go-micro/util/socket"
2015-01-13 23:31:27 +00:00
)
2015-05-23 17:40:53 +01:00
type rpcServer struct {
2019-01-07 14:44:40 +00:00
router *router
exit chan chan error
sync.RWMutex
opts Options
handlers map[string]Handler
subscribers map[Subscriber][]broker.Subscriber
// marks the serve as started
started bool
// used for first registration
registered bool
// subscribe to service name
subscriber broker.Subscriber
// graceful exit
wg *sync.WaitGroup
2015-01-13 23:31:27 +00:00
}
2015-05-26 22:39:48 +01:00
func newRpcServer(opts ...Option) Server {
options := newOptions(opts...)
router := newRpcRouter()
router.hdlrWrappers = options.HdlrWrappers
router.subWrappers = options.SubWrappers
2015-05-23 17:40:53 +01:00
return &rpcServer{
2019-01-07 14:44:40 +00:00
opts: options,
2019-06-12 12:05:34 +01:00
router: router,
handlers: make(map[string]Handler),
subscribers: make(map[Subscriber][]broker.Subscriber),
exit: make(chan chan error),
wg: wait(options.Context),
2015-05-23 17:40:53 +01:00
}
}
2015-01-13 23:31:27 +00:00
type rpcRouter struct {
h func(context.Context, Request, interface{}) error
m func(context.Context, Message) error
}
func (r rpcRouter) ProcessMessage(ctx context.Context, msg Message) error {
return r.m(ctx, msg)
}
func (r rpcRouter) ServeRequest(ctx context.Context, req Request, rsp Response) error {
return r.h(ctx, req, rsp)
}
// HandleEvent handles inbound messages to the service directly
// TODO: handle requests from an event. We won't send a response.
func (s *rpcServer) HandleEvent(e broker.Event) error {
// formatting horrible cruft
msg := e.Message()
if msg.Header == nil {
// create empty map in case of headers empty to avoid panic later
msg.Header = make(map[string]string)
}
// get codec
ct := msg.Header["Content-Type"]
// default content type
if len(ct) == 0 {
msg.Header["Content-Type"] = DefaultContentType
ct = DefaultContentType
}
// get codec
cf, err := s.newCodec(ct)
if err != nil {
return err
}
// copy headers
hdr := make(map[string]string)
for k, v := range msg.Header {
hdr[k] = v
}
// create context
ctx := metadata.NewContext(context.Background(), hdr)
// TODO: inspect message header
// Micro-Service means a request
// Micro-Topic means a message
rpcMsg := &rpcMessage{
topic: msg.Header["Micro-Topic"],
contentType: ct,
payload: &raw.Frame{msg.Body},
codec: cf,
header: msg.Header,
body: msg.Body,
}
// existing router
r := Router(s.router)
// if the router is present then execute it
if s.opts.Router != nil {
// create a wrapped function
handler := s.opts.Router.ProcessMessage
// execute the wrapper for it
for i := len(s.opts.SubWrappers); i > 0; i-- {
handler = s.opts.SubWrappers[i-1](handler)
}
// set the router
r = rpcRouter{m: handler}
}
return r.ProcessMessage(ctx, rpcMsg)
}
2019-01-08 20:32:47 +00:00
// ServeConn serves a single connection
func (s *rpcServer) ServeConn(sock transport.Socket) {
var wg sync.WaitGroup
var mtx sync.RWMutex
// streams are multiplexed on Micro-Stream or Micro-Id header
sockets := make(map[string]*socket.Socket)
2015-12-21 17:18:04 +00:00
defer func() {
// wait till done
wg.Wait()
// close underlying socket
2016-05-10 10:55:18 +01:00
sock.Close()
// close the sockets
mtx.Lock()
for id, psock := range sockets {
psock.Close()
delete(sockets, id)
}
mtx.Unlock()
// recover any panics
2015-12-21 17:18:04 +00:00
if r := recover(); r != nil {
2017-05-16 19:14:00 +01:00
log.Log("panic recovered: ", r)
log.Log(string(debug.Stack()))
2015-12-21 17:18:04 +00:00
}
}()
2016-05-13 15:58:53 +01:00
for {
var msg transport.Message
if err := sock.Recv(&msg); err != nil {
return
}
2015-01-13 23:31:27 +00:00
// check the message header for
// Micro-Service is a request
// Micro-Topic is a message
if t := msg.Header["Micro-Topic"]; len(t) > 0 {
// process the event
ev := newEvent(msg)
// TODO: handle the error event
if err := s.HandleEvent(ev); err != nil {
msg.Header["Micro-Error"] = err.Error()
}
// write back some 200
sock.Send(&transport.Message{
Header: msg.Header,
})
// we're done
continue
}
// business as usual
2019-08-16 14:42:45 +01:00
// use Micro-Stream as the stream identifier
2019-08-15 20:08:49 +01:00
// in the event its blank we'll always process
// on the same socket
id := msg.Header["Micro-Stream"]
// if there's no stream id then its a standard request
2019-08-16 14:42:45 +01:00
// use the Micro-Id
2019-08-15 20:08:49 +01:00
if len(id) == 0 {
id = msg.Header["Micro-Id"]
}
// we're starting processing
wg.Add(1)
// add to wait group if "wait" is opt-in
s.Lock()
swg := s.wg
s.Unlock()
if swg != nil {
swg.Add(1)
}
2018-05-26 09:41:41 +01:00
2019-08-15 20:08:49 +01:00
// check we have an existing socket
mtx.RLock()
psock, ok := sockets[id]
mtx.RUnlock()
// got the socket
if ok {
// accept the message
if err := psock.Accept(&msg); err != nil {
// delete the socket
mtx.Lock()
delete(sockets, id)
mtx.Unlock()
}
// done(1)
if swg != nil {
swg.Done()
2019-08-15 20:08:49 +01:00
}
wg.Done()
2019-08-15 20:08:49 +01:00
// continue to the next message
continue
}
// no socket was found
psock = socket.New()
psock.SetLocal(sock.Local())
psock.SetRemote(sock.Remote())
// load the socket
psock.Accept(&msg)
// save a new socket
mtx.Lock()
sockets[id] = psock
mtx.Unlock()
// now walk the usual path
2016-05-13 15:58:53 +01:00
// we use this Timeout header to set a server deadline
to := msg.Header["Timeout"]
// we use this Content-Type header to identify the codec needed
ct := msg.Header["Content-Type"]
2019-08-15 20:08:49 +01:00
// copy the message headers
2019-01-07 18:20:47 +00:00
hdr := make(map[string]string)
for k, v := range msg.Header {
hdr[k] = v
}
// set local/remote ips
hdr["Local"] = sock.Local()
hdr["Remote"] = sock.Remote()
2019-08-15 20:08:49 +01:00
// create new context with the metadata
2019-01-07 18:20:47 +00:00
ctx := metadata.NewContext(context.Background(), hdr)
2019-08-15 20:08:49 +01:00
// set the timeout from the header if we have it
2019-01-07 18:20:47 +00:00
if len(to) > 0 {
if n, err := strconv.ParseUint(to, 10, 64); err == nil {
ctx, _ = context.WithTimeout(ctx, time.Duration(n))
}
}
2019-08-15 20:08:49 +01:00
// if there's no content type default it
if len(ct) == 0 {
2019-01-08 20:32:47 +00:00
msg.Header["Content-Type"] = DefaultContentType
ct = DefaultContentType
}
2019-01-18 10:12:57 +00:00
// setup old protocol
cf := setupProtocol(&msg)
// no old codec
if cf == nil {
// TODO: needs better error handling
var err error
if cf, err = s.newCodec(ct); err != nil {
sock.Send(&transport.Message{
Header: map[string]string{
"Content-Type": "text/plain",
},
Body: []byte(err.Error()),
})
if swg != nil {
swg.Done()
}
wg.Done()
2019-01-18 10:12:57 +00:00
return
}
2016-05-13 15:58:53 +01:00
}
2015-11-25 19:50:05 +00:00
2019-08-15 20:08:49 +01:00
rcodec := newRpcCodec(&msg, psock, cf)
2019-08-26 12:33:59 +01:00
protocol := rcodec.String()
2019-08-15 20:08:49 +01:00
// check stream id
var stream bool
2019-08-26 12:33:59 +01:00
2019-08-15 20:08:49 +01:00
if v := getHeader("Micro-Stream", msg.Header); len(v) > 0 {
stream = true
}
2019-01-09 19:28:13 +00:00
2019-01-09 16:20:57 +00:00
// internal request
request := &rpcRequest{
2019-01-24 10:11:02 +00:00
service: getHeader("Micro-Service", msg.Header),
method: getHeader("Micro-Method", msg.Header),
endpoint: getHeader("Micro-Endpoint", msg.Header),
2019-01-09 16:20:57 +00:00
contentType: ct,
2019-01-13 12:15:35 +00:00
codec: rcodec,
2019-01-09 19:11:47 +00:00
header: msg.Header,
2019-01-09 16:20:57 +00:00
body: msg.Body,
2019-08-15 20:08:49 +01:00
socket: psock,
stream: stream,
2019-01-09 16:20:57 +00:00
}
2015-01-13 23:31:27 +00:00
2019-01-09 19:11:47 +00:00
// internal response
response := &rpcResponse{
header: make(map[string]string),
2019-08-15 20:08:49 +01:00
socket: psock,
2019-01-13 12:15:35 +00:00
codec: rcodec,
2019-01-09 19:11:47 +00:00
}
2019-01-08 20:32:47 +00:00
2019-01-09 19:11:47 +00:00
// set router
r := Router(s.router)
2019-01-11 15:49:54 +00:00
// if not nil use the router specified
if s.opts.Router != nil {
// create a wrapped function
handler := func(ctx context.Context, req Request, rsp interface{}) error {
return s.opts.Router.ServeRequest(ctx, req, rsp.(Response))
}
2019-01-08 20:32:47 +00:00
// execute the wrapper for it
for i := len(s.opts.HdlrWrappers); i > 0; i-- {
handler = s.opts.HdlrWrappers[i-1](handler)
}
2019-01-11 15:49:54 +00:00
// set the router
r = rpcRouter{h: handler}
2019-01-11 15:49:54 +00:00
}
2019-08-25 19:30:22 +01:00
// wait for processing to exit
wg.Add(1)
// process the outbound messages from the socket
go func(id string, psock *socket.Socket) {
defer func() {
2019-08-26 12:33:59 +01:00
// TODO: don't hack this but if its grpc just break out of the stream
// We do this because the underlying connection is h2 and its a stream
switch protocol {
case "grpc":
sock.Close()
}
2019-08-25 19:30:22 +01:00
wg.Done()
}()
for {
// get the message from our internal handler/stream
m := new(transport.Message)
if err := psock.Process(m); err != nil {
// delete the socket
mtx.Lock()
delete(sockets, id)
mtx.Unlock()
return
}
// send the message back over the socket
if err := sock.Send(m); err != nil {
return
}
}
}(id, psock)
2019-08-15 20:08:49 +01:00
// serve the request in a go routine as this may be a stream
go func(id string, psock *socket.Socket) {
defer psock.Close()
2019-08-15 20:08:49 +01:00
// serve the actual request using the request router
if serveRequestError := r.ServeRequest(ctx, request, response); serveRequestError != nil {
2019-08-15 20:08:49 +01:00
// write an error response
writeError := rcodec.Write(&codec.Message{
2019-08-15 20:08:49 +01:00
Header: msg.Header,
Error: serveRequestError.Error(),
2019-08-15 20:08:49 +01:00
Type: codec.Error,
}, nil)
// if the server request is an EOS error we let the socket know
// sometimes the socket is already closed on the other side, so we can ignore that error
alreadyClosed := serveRequestError == lastStreamResponseError && writeError == io.EOF
// could not write error response
if writeError != nil && !alreadyClosed {
log.Logf("rpc: unable to write error response: %v", writeError)
2019-08-15 20:08:49 +01:00
}
2019-01-22 13:55:04 +00:00
}
2019-08-15 20:08:49 +01:00
mtx.Lock()
delete(sockets, id)
mtx.Unlock()
// signal we're done
if swg != nil {
swg.Done()
}
// done with this socket
wg.Done()
2019-08-15 20:08:49 +01:00
}(id, psock)
}
2015-05-20 22:57:19 +01:00
}
func (s *rpcServer) newCodec(contentType string) (codec.NewCodec, error) {
if cf, ok := s.opts.Codecs[contentType]; ok {
return cf, nil
2015-11-25 19:50:05 +00:00
}
if cf, ok := DefaultCodecs[contentType]; ok {
2015-11-25 19:50:05 +00:00
return cf, nil
}
return nil, fmt.Errorf("Unsupported Content-Type: %s", contentType)
}
func (s *rpcServer) Options() Options {
s.RLock()
opts := s.opts
s.RUnlock()
return opts
2015-01-13 23:31:27 +00:00
}
2016-01-02 19:12:17 +00:00
func (s *rpcServer) Init(opts ...Option) error {
s.Lock()
2015-05-26 22:39:48 +01:00
for _, opt := range opts {
opt(&s.opts)
}
// update router if its the default
if s.opts.Router == nil {
r := newRpcRouter()
r.hdlrWrappers = s.opts.HdlrWrappers
r.serviceMap = s.router.serviceMap
r.subWrappers = s.opts.SubWrappers
s.router = r
}
s.Unlock()
2016-01-02 19:12:17 +00:00
return nil
2015-01-13 23:31:27 +00:00
}
func (s *rpcServer) NewHandler(h interface{}, opts ...HandlerOption) Handler {
2019-01-07 17:17:06 +00:00
return s.router.NewHandler(h, opts...)
2015-01-13 23:31:27 +00:00
}
func (s *rpcServer) Handle(h Handler) error {
s.Lock()
defer s.Unlock()
2019-01-07 17:17:06 +00:00
if err := s.router.Handle(h); err != nil {
return err
}
s.handlers[h.Name()] = h
return nil
2015-01-13 23:31:27 +00:00
}
func (s *rpcServer) NewSubscriber(topic string, sb interface{}, opts ...SubscriberOption) Subscriber {
return s.router.NewSubscriber(topic, sb, opts...)
}
func (s *rpcServer) Subscribe(sb Subscriber) error {
s.Lock()
defer s.Unlock()
if err := s.router.Subscribe(sb); err != nil {
return err
}
s.subscribers[sb] = nil
return nil
}
2016-01-27 12:23:18 +00:00
func (s *rpcServer) Register() error {
var err error
var advt, host, port string
// parse address for host, port
config := s.Options()
2015-11-11 18:22:04 +00:00
// check the advertise address first
// if it exists then use it, otherwise
// use the address
if len(config.Advertise) > 0 {
advt = config.Advertise
2015-11-11 18:22:04 +00:00
} else {
advt = config.Address
2015-11-11 18:22:04 +00:00
}
if cnt := strings.Count(advt, ":"); cnt >= 1 {
// ipv6 address in format [host]:port or ipv4 host:port
host, port, err = net.SplitHostPort(advt)
if err != nil {
return err
}
} else {
host = advt
2015-01-13 23:31:27 +00:00
}
2017-01-12 13:20:34 +00:00
addr, err := addr.Extract(host)
if err != nil {
return err
}
2019-02-04 10:29:10 +00:00
// make copy of metadata
md := make(metadata.Metadata)
for k, v := range config.Metadata {
md[k] = v
}
2019-08-14 21:32:28 +08:00
// mq-rpc(eg. nats) doesn't need the port. its addr is queue name.
if port != "" {
addr = mnet.HostPort(addr, port)
}
// register service
node := &registry.Node{
2016-01-02 00:38:57 +00:00
Id: config.Name + "-" + config.Id,
2019-08-14 21:32:28 +08:00
Address: addr,
2019-02-04 10:29:10 +00:00
Metadata: md,
}
node.Metadata["transport"] = config.Transport.String()
2016-01-04 01:27:05 +00:00
node.Metadata["broker"] = config.Broker.String()
node.Metadata["server"] = s.String()
2016-01-04 23:27:44 +00:00
node.Metadata["registry"] = config.Registry.String()
2019-01-18 12:30:39 +00:00
node.Metadata["protocol"] = "mucp"
2015-12-19 21:56:14 +00:00
s.RLock()
// Maps are ordered randomly, sort the keys for consistency
var handlerList []string
for n, e := range s.handlers {
// Only advertise non internal handlers
if !e.Options().Internal {
handlerList = append(handlerList, n)
}
}
sort.Strings(handlerList)
var subscriberList []Subscriber
for e := range s.subscribers {
// Only advertise non internal subscribers
if !e.Options().Internal {
subscriberList = append(subscriberList, e)
}
}
sort.Slice(subscriberList, func(i, j int) bool {
return subscriberList[i].Topic() > subscriberList[j].Topic()
})
2019-11-05 17:43:12 +00:00
endpoints := make([]*registry.Endpoint, 0, len(handlerList)+len(subscriberList))
for _, n := range handlerList {
endpoints = append(endpoints, s.handlers[n].Endpoints()...)
}
for _, e := range subscriberList {
endpoints = append(endpoints, e.Endpoints()...)
}
s.RUnlock()
service := &registry.Service{
Name: config.Name,
Version: config.Version,
Nodes: []*registry.Node{node},
Endpoints: endpoints,
}
2016-02-27 22:14:25 +00:00
s.Lock()
registered := s.registered
s.Unlock()
if !registered {
2019-02-15 17:20:09 +00:00
log.Logf("Registry [%s] Registering node: %s", config.Registry.String(), node.Id)
2016-02-27 22:14:25 +00:00
}
2016-01-27 12:23:18 +00:00
// create registry options
rOpts := []registry.RegisterOption{registry.RegisterTTL(config.RegisterTTL)}
2016-01-26 23:32:27 +00:00
if err := config.Registry.Register(service, rOpts...); err != nil {
return err
}
2016-02-27 22:14:25 +00:00
// already registered? don't need to register subscribers
if registered {
return nil
}
2016-02-27 22:14:25 +00:00
s.Lock()
defer s.Unlock()
s.registered = true
// subscribe to the topic with own name
sub, err := s.opts.Broker.Subscribe(config.Name, s.HandleEvent)
if err != nil {
return err
}
// save the subscriber
s.subscriber = sub
// subscribe for all of the subscribers
for sb := range s.subscribers {
2016-01-22 21:48:43 +00:00
var opts []broker.SubscribeOption
if queue := sb.Options().Queue; len(queue) > 0 {
2016-05-10 10:55:18 +01:00
opts = append(opts, broker.Queue(queue))
2016-01-22 21:48:43 +00:00
}
2019-05-24 20:06:27 +08:00
if cx := sb.Options().Context; cx != nil {
opts = append(opts, broker.SubscribeContext(cx))
}
2019-05-24 20:06:27 +08:00
if !sb.Options().AutoAck {
opts = append(opts, broker.DisableAutoAck())
}
sub, err := config.Broker.Subscribe(sb.Topic(), s.HandleEvent, opts...)
if err != nil {
return err
}
log.Logf("Subscribing %s to topic: %s", node.Id, sub.Topic())
s.subscribers[sb] = []broker.Subscriber{sub}
}
return nil
}
func (s *rpcServer) Deregister() error {
var err error
var advt, host, port string
config := s.Options()
2015-11-11 18:22:04 +00:00
// check the advertise address first
// if it exists then use it, otherwise
// use the address
if len(config.Advertise) > 0 {
advt = config.Advertise
2015-11-11 18:22:04 +00:00
} else {
advt = config.Address
2015-11-11 18:22:04 +00:00
}
if cnt := strings.Count(advt, ":"); cnt >= 1 {
// ipv6 address in format [host]:port or ipv4 host:port
host, port, err = net.SplitHostPort(advt)
if err != nil {
return err
}
} else {
host = advt
}
2017-01-12 13:20:34 +00:00
addr, err := addr.Extract(host)
if err != nil {
return err
}
2019-08-15 08:59:50 +01:00
// mq-rpc(eg. nats) doesn't need the port. its addr is queue name.
if port != "" {
addr = mnet.HostPort(addr, port)
}
node := &registry.Node{
2016-01-02 00:38:57 +00:00
Id: config.Name + "-" + config.Id,
2019-08-15 08:59:50 +01:00
Address: addr,
}
service := &registry.Service{
Name: config.Name,
Version: config.Version,
Nodes: []*registry.Node{node},
}
2019-02-15 17:20:09 +00:00
log.Logf("Registry [%s] Deregistering node: %s", config.Registry.String(), node.Id)
if err := config.Registry.Deregister(service); err != nil {
return err
}
s.Lock()
if !s.registered {
s.Unlock()
return nil
}
s.registered = false
// close the subscriber
if s.subscriber != nil {
s.subscriber.Unsubscribe()
s.subscriber = nil
}
for sb, subs := range s.subscribers {
for _, sub := range subs {
log.Logf("Unsubscribing %s from topic: %s", node.Id, sub.Topic())
sub.Unsubscribe()
}
s.subscribers[sb] = nil
}
s.Unlock()
return nil
2015-01-13 23:31:27 +00:00
}
2015-05-23 17:40:53 +01:00
func (s *rpcServer) Start() error {
s.RLock()
if s.started {
s.RUnlock()
return nil
}
s.RUnlock()
config := s.Options()
2015-01-13 23:31:27 +00:00
2019-01-24 13:22:17 +00:00
// start listening on the transport
ts, err := config.Transport.Listen(config.Address)
2015-01-13 23:31:27 +00:00
if err != nil {
return err
}
2019-01-22 12:18:33 +00:00
log.Logf("Transport [%s] Listening on %s", config.Transport.String(), ts.Addr())
// swap address
2019-01-24 13:22:17 +00:00
s.Lock()
addr := s.opts.Address
s.opts.Address = ts.Addr()
s.Unlock()
2019-01-24 13:22:17 +00:00
// connect to the broker
if err := config.Broker.Connect(); err != nil {
return err
}
2019-07-07 12:33:47 +01:00
bname := config.Broker.String()
2019-07-10 19:58:30 +01:00
log.Logf("Broker [%s] Connected to %s", bname, config.Broker.Address())
2019-01-24 13:22:17 +00:00
// use RegisterCheck func before register
if err = s.opts.RegisterCheck(s.opts.Context); err != nil {
log.Logf("Server %s-%s register check error: %s", config.Name, config.Id, err)
} else {
// announce self to the world
if err = s.Register(); err != nil {
log.Logf("Server %s-%s register error: %s", config.Name, config.Id, err)
}
2019-01-24 13:22:17 +00:00
}
exit := make(chan bool)
2018-11-15 19:55:13 +00:00
go func() {
for {
2019-01-24 13:22:17 +00:00
// listen for connections
2019-01-08 20:32:47 +00:00
err := ts.Accept(s.ServeConn)
2018-11-15 19:55:13 +00:00
2019-01-24 13:22:17 +00:00
// TODO: listen for messages
// msg := broker.Exchange(service).Consume()
2018-11-15 19:55:13 +00:00
select {
2019-01-24 13:22:17 +00:00
// check if we're supposed to exit
2018-11-15 19:55:13 +00:00
case <-exit:
return
// check the error and backoff
2019-01-24 13:22:17 +00:00
default:
if err != nil {
log.Logf("Accept error: %v", err)
time.Sleep(time.Second)
continue
}
2018-11-15 19:55:13 +00:00
}
// no error just exit
return
}
}()
2015-01-13 23:31:27 +00:00
go func() {
2019-01-24 16:08:04 +00:00
t := new(time.Ticker)
2019-01-24 13:22:17 +00:00
// only process if it exists
2019-01-24 16:08:04 +00:00
if s.opts.RegisterInterval > time.Duration(0) {
// new ticker
t = time.NewTicker(s.opts.RegisterInterval)
2019-01-24 13:22:17 +00:00
}
// return error chan
var ch chan error
Loop:
for {
select {
// register self on interval
case <-t.C:
s.RLock()
registered := s.registered
s.RUnlock()
if err = s.opts.RegisterCheck(s.opts.Context); err != nil && registered {
log.Logf("Server %s-%s register check error: %s, deregister it", config.Name, config.Id, err)
// deregister self in case of error
if err := s.Deregister(); err != nil {
log.Logf("Server %s-%s deregister error: %s", config.Name, config.Id, err)
}
} else {
if err := s.Register(); err != nil {
log.Logf("Server %s-%s register error: %s", config.Name, config.Id, err)
}
2019-01-24 13:22:17 +00:00
}
// wait for exit
case ch = <-s.exit:
t.Stop()
close(exit)
break Loop
}
}
// deregister self
if err := s.Deregister(); err != nil {
log.Logf("Server %s-%s deregister error: %s", config.Name, config.Id, err)
2019-01-24 13:22:17 +00:00
}
s.Lock()
swg := s.wg
s.Unlock()
// wait for requests to finish
if swg != nil {
swg.Wait()
}
// close transport listener
2015-05-20 22:57:19 +01:00
ch <- ts.Close()
// disconnect the broker
config.Broker.Disconnect()
// swap back address
2019-01-24 13:22:17 +00:00
s.Lock()
s.opts.Address = addr
s.Unlock()
2015-01-13 23:31:27 +00:00
}()
// mark the server as started
s.Lock()
s.started = true
s.Unlock()
2019-01-22 12:18:33 +00:00
return nil
2015-01-13 23:31:27 +00:00
}
2015-05-23 17:40:53 +01:00
func (s *rpcServer) Stop() error {
s.RLock()
if !s.started {
s.RUnlock()
return nil
}
s.RUnlock()
2015-01-13 23:31:27 +00:00
ch := make(chan error)
s.exit <- ch
var err error
select {
case err = <-ch:
2019-08-23 15:07:08 +01:00
s.Lock()
s.started = false
2019-08-23 15:07:08 +01:00
s.Unlock()
}
return err
2015-01-13 23:31:27 +00:00
}
2015-12-19 21:56:14 +00:00
func (s *rpcServer) String() string {
2019-06-08 19:40:44 +01:00
return "mucp"
2015-12-19 21:56:14 +00:00
}